code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/run_loop.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/background_sync/background_sync_controller_impl.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "content/public/browser/background_sync_parameters.h"
#include "content/public/test/background_sync_test_util.h"
#include "content/public/test/browser_test_utils.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/browser/background_sync/background_sync_controller_factory.h"
#include "weblayer/browser/background_sync/background_sync_delegate_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
#if !BUILDFLAG(IS_ANDROID)
#include "components/keep_alive_registry/keep_alive_registry.h"
#include "components/keep_alive_registry/keep_alive_state_observer.h"
namespace {
class TestKeepAliveStateObserver : public KeepAliveStateObserver {
public:
TestKeepAliveStateObserver() {
KeepAliveRegistry::GetInstance()->AddObserver(this);
}
~TestKeepAliveStateObserver() override {
KeepAliveRegistry::GetInstance()->RemoveObserver(this);
}
void OnKeepAliveStateChanged(bool is_keeping_alive) override {
if (is_keeping_alive_loop_ && !is_keeping_alive)
is_keeping_alive_loop_->Quit();
}
void OnKeepAliveRestartStateChanged(bool can_restart) override {}
void WaitUntilNoKeepAlives() {
if (!KeepAliveRegistry::GetInstance()->IsKeepingAlive())
return;
is_keeping_alive_loop_ = std::make_unique<base::RunLoop>();
is_keeping_alive_loop_->Run();
is_keeping_alive_loop_ = nullptr;
CHECK(!KeepAliveRegistry::GetInstance()->IsKeepingAlive());
}
private:
std::unique_ptr<base::RunLoop> is_keeping_alive_loop_;
};
} // namespace
#endif // !BUILDFLAG(IS_ANDROID)
namespace {
const char kExampleUrl[] = "https://www.example.com/";
const char kTag[] = "test_tag";
} // namespace
namespace weblayer {
class BackgroundSyncBrowserTest : public WebLayerBrowserTest {
public:
BackgroundSyncBrowserTest() = default;
~BackgroundSyncBrowserTest() override = default;
void SetUpOnMainThread() override {
sync_event_received_ = std::make_unique<base::RunLoop>();
content::background_sync_test_util::SetIgnoreNetworkChanges(
/* ignore= */ true);
https_server_ = std::make_unique<net::EmbeddedTestServer>(
net::EmbeddedTestServer::TYPE_HTTPS);
https_server_->RegisterRequestHandler(base::BindRepeating(
&BackgroundSyncBrowserTest::HandleRequest, base::Unretained(this)));
https_server_->AddDefaultHandlers(
base::FilePath(FILE_PATH_LITERAL("weblayer/test/data")));
ASSERT_TRUE(https_server_->Start());
}
// Intercepts all requests.
std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
const net::test_server::HttpRequest& request) {
if (request.GetURL().query() == "syncreceived") {
if (sync_event_received_)
sync_event_received_->Quit();
}
// The default handlers will take care of this request.
return nullptr;
}
#if !BUILDFLAG(IS_ANDROID)
void PostRunTestOnMainThread() override {
keep_alive_observer_.WaitUntilNoKeepAlives();
WebLayerBrowserTest::PostRunTestOnMainThread();
}
#endif // !BUILDFLAG(IS_ANDROID)
protected:
content::WebContents* web_contents() {
return static_cast<TabImpl*>(shell()->tab())->web_contents();
}
std::unique_ptr<base::RunLoop> sync_event_received_;
std::unique_ptr<net::EmbeddedTestServer> https_server_;
#if !BUILDFLAG(IS_ANDROID)
TestKeepAliveStateObserver keep_alive_observer_;
#endif // !BUILDFLAG(IS_ANDROID)
};
IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, GetBackgroundSyncController) {
EXPECT_TRUE(BackgroundSyncControllerFactory::GetForBrowserContext(
GetBrowserContext()));
}
IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, ZeroSiteEngagementPenalty) {
// TODO(crbug.com/1091211): Update when we add support for Periodic Background
// Sync.
auto* controller = BackgroundSyncControllerFactory::GetForBrowserContext(
GetBrowserContext());
ASSERT_TRUE(controller);
url::Origin origin = url::Origin::Create(GURL(kExampleUrl));
content::BackgroundSyncRegistration registration;
registration.set_origin(origin);
// min interval >=0 implies Periodic Background Sync.
blink::mojom::SyncRegistrationOptions options(
kTag,
/* min_interval= */ base::Hours(12).InMilliseconds());
*registration.options() = std::move(options);
// First attempt.
registration.set_num_attempts(0);
content::BackgroundSyncParameters parameters;
base::TimeDelta delay = controller->GetNextEventDelay(
registration, ¶meters,
/* time_till_soonest_scheduled_event_for_origin= */
base::TimeDelta::Max());
EXPECT_EQ(delay, base::TimeDelta::Max());
}
#if BUILDFLAG(IS_ANDROID)
// TODO(crbug.com/1154332): Fix flaky test.
IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest,
DISABLED_BackgroundSyncNotDisabled) {
auto* controller = BackgroundSyncControllerFactory::GetForBrowserContext(
GetBrowserContext());
ASSERT_TRUE(controller);
// TODO(crbug.com/1087486, 1091211): Update logic here if we need to support
// Android L when we add browser wakeup logic.
content::BackgroundSyncParameters parameters;
controller->GetParameterOverrides(¶meters);
EXPECT_FALSE(parameters.disable);
}
#endif // defined (OS_ANDROID)
IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, ContentSettings) {
auto* browser_context = GetBrowserContext();
auto* controller =
BackgroundSyncControllerFactory::GetForBrowserContext(browser_context);
ASSERT_TRUE(controller);
url::Origin origin = url::Origin::Create(GURL(kExampleUrl));
controller->AddToTrackedOrigins(origin);
ASSERT_TRUE(controller->IsOriginTracked(origin));
auto* host_content_settings_map =
HostContentSettingsMapFactory::GetForBrowserContext(browser_context);
ASSERT_TRUE(host_content_settings_map);
host_content_settings_map->SetContentSettingDefaultScope(
/* primary_url= */ GURL(kExampleUrl),
/* secondary_url= */ GURL(kExampleUrl),
ContentSettingsType::BACKGROUND_SYNC, CONTENT_SETTING_BLOCK);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(controller->IsOriginTracked(origin));
}
IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, NormalProfile) {
// TODO(crbug.com/1087486, 1091211): Make this use
// BackgroundSyncController::ScheduleBrowserWakeup() once we support waking
// the browser up.
auto delegate =
std::make_unique<BackgroundSyncDelegateImpl>(GetBrowserContext());
ASSERT_TRUE(delegate);
EXPECT_FALSE(delegate->IsProfileOffTheRecord());
}
IN_PROC_BROWSER_TEST_F(BackgroundSyncBrowserTest, SyncEventFired) {
content::background_sync_test_util::SetOnline(web_contents(), false);
NavigateAndWaitForCompletion(
https_server_->GetURL("/background_sync_browsertest.html"), shell());
content::background_sync_test_util::SetOnline(web_contents(), true);
sync_event_received_->Run();
}
class IncognitoBackgroundSyncBrowserTest : public BackgroundSyncBrowserTest {
public:
IncognitoBackgroundSyncBrowserTest() { SetShellStartsInIncognitoMode(); }
};
IN_PROC_BROWSER_TEST_F(IncognitoBackgroundSyncBrowserTest,
DISABLED_OffTheRecordProfile) {
base::ScopedAllowBlockingForTesting allow_blocking;
// TODO(crbug.com/1087486, 1091211): Make this use
// BackgroundSyncController::ScheduleBrowserWakeup() once we support waking
// the browser up.
auto delegate =
std::make_unique<BackgroundSyncDelegateImpl>(GetBrowserContext());
EXPECT_TRUE(delegate->IsProfileOffTheRecord());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_sync/background_sync_browsertest.cc | C++ | unknown | 8,273 |
// 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/background_sync/background_sync_controller_factory.h"
#include "base/no_destructor.h"
#include "components/background_sync/background_sync_controller_impl.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "weblayer/browser/background_sync/background_sync_delegate_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
BackgroundSyncControllerImpl*
BackgroundSyncControllerFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
// This is safe because BuildServiceInstanceFor(), which this method calls,
// returns a pointer to a BackgroundSyncControllerImpl object.
return static_cast<BackgroundSyncControllerImpl*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
BackgroundSyncControllerFactory*
BackgroundSyncControllerFactory::GetInstance() {
static base::NoDestructor<BackgroundSyncControllerFactory> factory;
return factory.get();
}
BackgroundSyncControllerFactory::BackgroundSyncControllerFactory()
: BrowserContextKeyedServiceFactory(
"BackgroundSyncService",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
BackgroundSyncControllerFactory::~BackgroundSyncControllerFactory() = default;
KeyedService* BackgroundSyncControllerFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new BackgroundSyncControllerImpl(
context, std::make_unique<BackgroundSyncDelegateImpl>(context));
}
content::BrowserContext*
BackgroundSyncControllerFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
// Background sync operates in incognito mode, and as incognito profiles in
// Weblayer are not tied to regular profiles, return |context| itself.
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_sync/background_sync_controller_factory.cc | C++ | unknown | 2,084 |
// 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_BACKGROUND_SYNC_BACKGROUND_SYNC_CONTROLLER_FACTORY_H_
#define WEBLAYER_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_CONTROLLER_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class BackgroundSyncControllerImpl;
namespace content {
class BrowserContext;
}
namespace weblayer {
// Creates and maintains a BackgroundSyncController instance per BrowserContext.
class BackgroundSyncControllerFactory
: public BrowserContextKeyedServiceFactory {
public:
static BackgroundSyncControllerImpl* GetForBrowserContext(
content::BrowserContext* browser_context);
static BackgroundSyncControllerFactory* GetInstance();
BackgroundSyncControllerFactory(const BackgroundSyncControllerFactory&) =
delete;
BackgroundSyncControllerFactory& operator=(
const BackgroundSyncControllerFactory&) = delete;
private:
friend class base::NoDestructor<BackgroundSyncControllerFactory>;
BackgroundSyncControllerFactory();
~BackgroundSyncControllerFactory() override;
// BrowserContextKeyedServiceFactory methods:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_CONTROLLER_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_sync/background_sync_controller_factory.h | C++ | unknown | 1,590 |
// 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/background_sync/background_sync_delegate_impl.h"
#include "build/build_config.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
BackgroundSyncDelegateImpl::BackgroundSyncDelegateImpl(
content::BrowserContext* browser_context)
: browser_context_(browser_context) {
DCHECK(browser_context_);
}
BackgroundSyncDelegateImpl::~BackgroundSyncDelegateImpl() = default;
#if !BUILDFLAG(IS_ANDROID)
std::unique_ptr<content::BackgroundSyncController::BackgroundSyncEventKeepAlive>
BackgroundSyncDelegateImpl::CreateBackgroundSyncEventKeepAlive() {
return nullptr;
}
#endif // !BUILDFLAG(IS_ANDROID)
void BackgroundSyncDelegateImpl::GetUkmSourceId(
const url::Origin& origin,
base::OnceCallback<void(absl::optional<ukm::SourceId>)> callback) {
// The exact URL which registered the Background Sync event is not saved,
// and the current main frame URL might not correspond to |origin|. Thus, we
// associate a new source ID with the origin.
// The only way WebLayer can lose history information is through the
// clearBrowsingHistory() API which also deletes all existing service workers.
// Therefore, if this method is called, it's safe to assume that the origin
// associated with the Background Sync registration is in WebLayer's browsing
// history. It's okay to log UKM for it.
ukm::SourceId source_id = ukm::ConvertToSourceId(
ukm::AssignNewSourceId(), ukm::SourceIdType::HISTORY_ID);
ukm::UkmRecorder* recorder = ukm::UkmRecorder::Get();
DCHECK(recorder);
recorder->UpdateSourceURL(source_id, origin.GetURL());
std::move(callback).Run(source_id);
}
void BackgroundSyncDelegateImpl::Shutdown() {
// Clear the BrowserContext as we're not supposed to use it anymore.
browser_context_ = nullptr;
}
HostContentSettingsMap*
BackgroundSyncDelegateImpl::GetHostContentSettingsMap() {
return HostContentSettingsMapFactory::GetForBrowserContext(browser_context_);
}
bool BackgroundSyncDelegateImpl::IsProfileOffTheRecord() {
DCHECK(browser_context_);
return browser_context_->IsOffTheRecord();
}
void BackgroundSyncDelegateImpl::NoteSuspendedPeriodicSyncOrigins(
std::set<url::Origin> suspended_origins) {
// TODO(crbug.com/1091211): Consider site engagement when adding support for
// Periodic Background Sync.
}
int BackgroundSyncDelegateImpl::GetSiteEngagementPenalty(const GURL& url) {
// TODO(crbug.com/1091211): Consider site engagement when adding support for
// Periodic Background Sync.
return 0;
}
#if BUILDFLAG(IS_ANDROID)
void BackgroundSyncDelegateImpl::ScheduleBrowserWakeUpWithDelay(
blink::mojom::BackgroundSyncType sync_type,
base::TimeDelta delay) {
// TODO(crbug.com/1087486, 1091211): Add logic to wake up the browser.
}
void BackgroundSyncDelegateImpl::CancelBrowserWakeup(
blink::mojom::BackgroundSyncType sync_type) {
// TODO(crbug.com/1087486, 1091211): Add logic to wake up the browser.
}
bool BackgroundSyncDelegateImpl::ShouldDisableBackgroundSync() {
// TODO(crbug.com/1087486, 1091211): Add logic here if we need to support
// Android L.
return false;
}
bool BackgroundSyncDelegateImpl::ShouldDisableAndroidNetworkDetection() {
// TODO(crbug.com/1141778): Remove this once waking up the WebLayer
// embedder is supported.
return true;
}
#endif // BUILDFLAG(IS_ANDROID)
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_sync/background_sync_delegate_impl.cc | C++ | unknown | 3,751 |
// 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_BACKGROUND_SYNC_BACKGROUND_SYNC_DELEGATE_IMPL_H_
#define WEBLAYER_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_DELEGATE_IMPL_H_
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "components/background_sync/background_sync_delegate.h"
#include "url/origin.h"
namespace content {
class BrowserContext;
} // namespace content
namespace weblayer {
// WebLayer's customization of the logic in components/background_sync.
class BackgroundSyncDelegateImpl
: public background_sync::BackgroundSyncDelegate {
public:
explicit BackgroundSyncDelegateImpl(content::BrowserContext* browser_context);
~BackgroundSyncDelegateImpl() override;
#if !BUILDFLAG(IS_ANDROID)
std::unique_ptr<
content::BackgroundSyncController::BackgroundSyncEventKeepAlive>
CreateBackgroundSyncEventKeepAlive() override;
#endif // !BUILDFLAG(IS_ANDROID)
void GetUkmSourceId(const url::Origin& origin,
base::OnceCallback<void(absl::optional<ukm::SourceId>)>
callback) override;
void Shutdown() override;
HostContentSettingsMap* GetHostContentSettingsMap() override;
bool IsProfileOffTheRecord() override;
void NoteSuspendedPeriodicSyncOrigins(
std::set<url::Origin> suspended_origins) override;
int GetSiteEngagementPenalty(const GURL& url) override;
#if BUILDFLAG(IS_ANDROID)
void ScheduleBrowserWakeUpWithDelay(
blink::mojom::BackgroundSyncType sync_type,
base::TimeDelta delay) override;
void CancelBrowserWakeup(blink::mojom::BackgroundSyncType sync_type) override;
bool ShouldDisableBackgroundSync() override;
bool ShouldDisableAndroidNetworkDetection() override;
#endif // BUILDFLAG(IS_ANDROID)
private:
raw_ptr<content::BrowserContext> browser_context_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BACKGROUND_SYNC_BACKGROUND_SYNC_DELEGATE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/background_sync/background_sync_delegate_impl.h | C++ | unknown | 2,035 |
// 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/bluetooth/weblayer_bluetooth_chooser_android_delegate.h"
#include "base/android/jni_android.h"
#include "components/security_state/content/content_utils.h"
#include "weblayer/browser/java/jni/WebLayerBluetoothChooserAndroidDelegate_jni.h"
namespace weblayer {
WebLayerBluetoothChooserAndroidDelegate::
WebLayerBluetoothChooserAndroidDelegate() {
JNIEnv* env = base::android::AttachCurrentThread();
java_delegate_.Reset(
Java_WebLayerBluetoothChooserAndroidDelegate_create(env));
}
WebLayerBluetoothChooserAndroidDelegate::
~WebLayerBluetoothChooserAndroidDelegate() = default;
base::android::ScopedJavaLocalRef<jobject>
WebLayerBluetoothChooserAndroidDelegate::GetJavaObject() {
return base::android::ScopedJavaLocalRef<jobject>(java_delegate_);
}
security_state::SecurityLevel
WebLayerBluetoothChooserAndroidDelegate::GetSecurityLevel(
content::WebContents* web_contents) {
auto state = security_state::GetVisibleSecurityState(web_contents);
return security_state::GetSecurityLevel(
*state,
/*used_policy_installed_certificate=*/false);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/bluetooth/weblayer_bluetooth_chooser_android_delegate.cc | C++ | unknown | 1,283 |
// 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_BLUETOOTH_WEBLAYER_BLUETOOTH_CHOOSER_ANDROID_DELEGATE_H_
#define WEBLAYER_BROWSER_BLUETOOTH_WEBLAYER_BLUETOOTH_CHOOSER_ANDROID_DELEGATE_H_
#include "components/permissions/android/bluetooth_chooser_android_delegate.h"
#include "base/android/scoped_java_ref.h"
namespace weblayer {
// The implementation of BluetoothChooserAndroidDelegate for WebLayer.
class WebLayerBluetoothChooserAndroidDelegate
: public permissions::BluetoothChooserAndroidDelegate {
public:
WebLayerBluetoothChooserAndroidDelegate();
WebLayerBluetoothChooserAndroidDelegate(
const WebLayerBluetoothChooserAndroidDelegate&) = delete;
WebLayerBluetoothChooserAndroidDelegate& operator=(
const WebLayerBluetoothChooserAndroidDelegate&) = delete;
~WebLayerBluetoothChooserAndroidDelegate() override;
// BluetoothChooserAndroidDelegate implementation:
base::android::ScopedJavaLocalRef<jobject> GetJavaObject() override;
security_state::SecurityLevel GetSecurityLevel(
content::WebContents* web_contents) override;
private:
base::android::ScopedJavaGlobalRef<jobject> java_delegate_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BLUETOOTH_WEBLAYER_BLUETOOTH_CHOOSER_ANDROID_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/bluetooth/weblayer_bluetooth_chooser_android_delegate.h | C++ | unknown | 1,382 |
// 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/bluetooth/weblayer_bluetooth_chooser_context_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/permissions/contexts/bluetooth_chooser_context.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
WebLayerBluetoothChooserContextFactory*
WebLayerBluetoothChooserContextFactory::GetInstance() {
static base::NoDestructor<WebLayerBluetoothChooserContextFactory> factory;
return factory.get();
}
// static
permissions::BluetoothChooserContext*
WebLayerBluetoothChooserContextFactory::GetForBrowserContext(
content::BrowserContext* context) {
return static_cast<permissions::BluetoothChooserContext*>(
GetInstance()->GetServiceForBrowserContext(context, /*create=*/true));
}
// static
permissions::BluetoothChooserContext*
WebLayerBluetoothChooserContextFactory::GetForBrowserContextIfExists(
content::BrowserContext* context) {
return static_cast<permissions::BluetoothChooserContext*>(
GetInstance()->GetServiceForBrowserContext(context, /*create=*/false));
}
WebLayerBluetoothChooserContextFactory::WebLayerBluetoothChooserContextFactory()
: BrowserContextKeyedServiceFactory(
"BluetoothChooserContext",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
WebLayerBluetoothChooserContextFactory::
~WebLayerBluetoothChooserContextFactory() = default;
KeyedService* WebLayerBluetoothChooserContextFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new permissions::BluetoothChooserContext(context);
}
content::BrowserContext*
WebLayerBluetoothChooserContextFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
void WebLayerBluetoothChooserContextFactory::BrowserContextShutdown(
content::BrowserContext* context) {
auto* bluetooth_chooser_context = GetForBrowserContextIfExists(context);
if (bluetooth_chooser_context)
bluetooth_chooser_context->FlushScheduledSaveSettingsCalls();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/bluetooth/weblayer_bluetooth_chooser_context_factory.cc | C++ | unknown | 2,335 |
// 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_BLUETOOTH_WEBLAYER_BLUETOOTH_CHOOSER_CONTEXT_FACTORY_H_
#define WEBLAYER_BROWSER_BLUETOOTH_WEBLAYER_BLUETOOTH_CHOOSER_CONTEXT_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace permissions {
class BluetoothChooserContext;
}
namespace weblayer {
class WebLayerBluetoothChooserContextFactory
: public BrowserContextKeyedServiceFactory {
public:
static permissions::BluetoothChooserContext* GetForBrowserContext(
content::BrowserContext* context);
static permissions::BluetoothChooserContext* GetForBrowserContextIfExists(
content::BrowserContext* context);
static WebLayerBluetoothChooserContextFactory* GetInstance();
WebLayerBluetoothChooserContextFactory(
const WebLayerBluetoothChooserContextFactory&) = delete;
WebLayerBluetoothChooserContextFactory& operator=(
const WebLayerBluetoothChooserContextFactory&) = delete;
private:
friend base::NoDestructor<WebLayerBluetoothChooserContextFactory>;
WebLayerBluetoothChooserContextFactory();
~WebLayerBluetoothChooserContextFactory() override;
// BrowserContextKeyedServiceFactory implementation:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
void BrowserContextShutdown(content::BrowserContext* context) override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BLUETOOTH_WEBLAYER_BLUETOOTH_CHOOSER_CONTEXT_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/bluetooth/weblayer_bluetooth_chooser_context_factory.h | C++ | unknown | 1,748 |
// 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/bluetooth/weblayer_bluetooth_delegate_impl_client.h"
#include "build/build_config.h"
#include "content/public/browser/render_frame_host.h"
#include "weblayer/browser/bluetooth/weblayer_bluetooth_chooser_context_factory.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/permissions/android/bluetooth_chooser_android.h"
#include "components/permissions/android/bluetooth_scanning_prompt_android.h"
#include "weblayer/browser/bluetooth/weblayer_bluetooth_chooser_android_delegate.h"
#include "weblayer/browser/bluetooth/weblayer_bluetooth_scanning_prompt_android_delegate.h"
#endif // BUILDFLAG(IS_ANDROID)
namespace weblayer {
WebLayerBluetoothDelegateImplClient::WebLayerBluetoothDelegateImplClient() =
default;
WebLayerBluetoothDelegateImplClient::~WebLayerBluetoothDelegateImplClient() =
default;
permissions::BluetoothChooserContext*
WebLayerBluetoothDelegateImplClient::GetBluetoothChooserContext(
content::RenderFrameHost* frame) {
return WebLayerBluetoothChooserContextFactory::GetForBrowserContext(
frame->GetBrowserContext());
}
std::unique_ptr<content::BluetoothChooser>
WebLayerBluetoothDelegateImplClient::RunBluetoothChooser(
content::RenderFrameHost* frame,
const content::BluetoothChooser::EventHandler& event_handler) {
#if BUILDFLAG(IS_ANDROID)
// TODO(https://crbug.com/1231932): Return nullptr if suppressed in vr.
return std::make_unique<permissions::BluetoothChooserAndroid>(
frame, event_handler,
std::make_unique<WebLayerBluetoothChooserAndroidDelegate>());
#else
// Web Bluetooth is not supported for desktop in WebLayer.
return nullptr;
#endif
}
std::unique_ptr<content::BluetoothScanningPrompt>
WebLayerBluetoothDelegateImplClient::ShowBluetoothScanningPrompt(
content::RenderFrameHost* frame,
const content::BluetoothScanningPrompt::EventHandler& event_handler) {
#if BUILDFLAG(IS_ANDROID)
return std::make_unique<permissions::BluetoothScanningPromptAndroid>(
frame, event_handler,
std::make_unique<WebLayerBluetoothScanningPromptAndroidDelegate>());
#else
// Web Bluetooth is not supported for desktop in WebLayer.
return nullptr;
#endif
}
void WebLayerBluetoothDelegateImplClient::ShowBluetoothDevicePairDialog(
content::RenderFrameHost* frame,
const std::u16string& device_identifier,
content::BluetoothDelegate::PairPromptCallback callback,
content::BluetoothDelegate::PairingKind,
const absl::optional<std::u16string>& pin) {
// Web Bluetooth is not supported for desktop in WebLayer and Android already
// bonds on demand, so this should not be called on any platform.
std::move(callback).Run(content::BluetoothDelegate::PairPromptResult(
content::BluetoothDelegate::PairPromptStatus::kCancelled));
NOTREACHED();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/bluetooth/weblayer_bluetooth_delegate_impl_client.cc | C++ | unknown | 2,960 |
// 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_BLUETOOTH_WEBLAYER_BLUETOOTH_DELEGATE_IMPL_CLIENT_H_
#define WEBLAYER_BROWSER_BLUETOOTH_WEBLAYER_BLUETOOTH_DELEGATE_IMPL_CLIENT_H_
#include <memory>
#include "components/permissions/bluetooth_chooser_controller.h"
#include "components/permissions/bluetooth_delegate_impl.h"
#include "content/public/browser/bluetooth_delegate.h"
namespace content {
class RenderFrameHost;
} // namespace content
namespace permissions {
class BluetoothChooserContext;
} // namespace permissions
namespace weblayer {
// Provides embedder-level functionality to BluetoothDelegateImpl in WebLayer.
class WebLayerBluetoothDelegateImplClient
: public permissions::BluetoothDelegateImpl::Client {
public:
WebLayerBluetoothDelegateImplClient();
~WebLayerBluetoothDelegateImplClient() override;
WebLayerBluetoothDelegateImplClient(
const WebLayerBluetoothDelegateImplClient&) = delete;
WebLayerBluetoothDelegateImplClient& operator=(
const WebLayerBluetoothDelegateImplClient&) = delete;
// BluetoothDelegateImpl::Client implementation:
permissions::BluetoothChooserContext* GetBluetoothChooserContext(
content::RenderFrameHost* frame) override;
std::unique_ptr<content::BluetoothChooser> RunBluetoothChooser(
content::RenderFrameHost* frame,
const content::BluetoothChooser::EventHandler& event_handler) override;
std::unique_ptr<content::BluetoothScanningPrompt> ShowBluetoothScanningPrompt(
content::RenderFrameHost* frame,
const content::BluetoothScanningPrompt::EventHandler& event_handler)
override;
void ShowBluetoothDevicePairDialog(
content::RenderFrameHost* frame,
const std::u16string& device_identifier,
content::BluetoothDelegate::PairPromptCallback callback,
content::BluetoothDelegate::PairingKind,
const absl::optional<std::u16string>& pin) override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BLUETOOTH_WEBLAYER_BLUETOOTH_DELEGATE_IMPL_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/bluetooth/weblayer_bluetooth_delegate_impl_client.h | C++ | unknown | 2,133 |
// 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/bluetooth/weblayer_bluetooth_scanning_prompt_android_delegate.h"
#include "base/android/jni_android.h"
#include "components/security_state/content/content_utils.h"
#include "weblayer/browser/java/jni/WebLayerBluetoothScanningPromptAndroidDelegate_jni.h"
namespace weblayer {
WebLayerBluetoothScanningPromptAndroidDelegate::
WebLayerBluetoothScanningPromptAndroidDelegate() {
JNIEnv* env = base::android::AttachCurrentThread();
java_delegate_.Reset(
Java_WebLayerBluetoothScanningPromptAndroidDelegate_create(env));
}
WebLayerBluetoothScanningPromptAndroidDelegate::
~WebLayerBluetoothScanningPromptAndroidDelegate() = default;
base::android::ScopedJavaLocalRef<jobject>
WebLayerBluetoothScanningPromptAndroidDelegate::GetJavaObject() {
return base::android::ScopedJavaLocalRef<jobject>(java_delegate_);
}
security_state::SecurityLevel
WebLayerBluetoothScanningPromptAndroidDelegate::GetSecurityLevel(
content::WebContents* web_contents) {
auto state = security_state::GetVisibleSecurityState(web_contents);
return security_state::GetSecurityLevel(
*state,
/*used_policy_installed_certificate=*/false);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/bluetooth/weblayer_bluetooth_scanning_prompt_android_delegate.cc | C++ | unknown | 1,347 |
// 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_BLUETOOTH_WEBLAYER_BLUETOOTH_SCANNING_PROMPT_ANDROID_DELEGATE_H_
#define WEBLAYER_BROWSER_BLUETOOTH_WEBLAYER_BLUETOOTH_SCANNING_PROMPT_ANDROID_DELEGATE_H_
#include "components/permissions/android/bluetooth_scanning_prompt_android_delegate.h"
#include "base/android/scoped_java_ref.h"
namespace weblayer {
// The implementation of BluetoothScanningPromptAndroidDelegate for WebLayer.
class WebLayerBluetoothScanningPromptAndroidDelegate
: public permissions::BluetoothScanningPromptAndroidDelegate {
public:
WebLayerBluetoothScanningPromptAndroidDelegate();
WebLayerBluetoothScanningPromptAndroidDelegate(
const WebLayerBluetoothScanningPromptAndroidDelegate&) = delete;
WebLayerBluetoothScanningPromptAndroidDelegate& operator=(
const WebLayerBluetoothScanningPromptAndroidDelegate&) = delete;
~WebLayerBluetoothScanningPromptAndroidDelegate() override;
// permissions::BluetoothScanningPromptAndroidDelegate implementation:
base::android::ScopedJavaLocalRef<jobject> GetJavaObject() override;
security_state::SecurityLevel GetSecurityLevel(
content::WebContents* web_contents) override;
private:
base::android::ScopedJavaGlobalRef<jobject> java_delegate_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BLUETOOTH_WEBLAYER_BLUETOOTH_SCANNING_PROMPT_ANDROID_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/bluetooth/weblayer_bluetooth_scanning_prompt_android_delegate.h | C++ | unknown | 1,497 |
// 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/browser_context_impl.h"
#include "base/memory/raw_ptr.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "components/background_sync/background_sync_controller_impl.h"
#include "components/blocked_content/safe_browsing_triggered_popup_blocker.h"
#include "components/client_hints/browser/client_hints.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/download/public/common/in_progress_download_manager.h"
#include "components/embedder_support/pref_names.h"
#include "components/heavy_ad_intervention/heavy_ad_service.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/language/core/browser/language_prefs.h"
#include "components/origin_trials/browser/origin_trials.h"
#include "components/payments/core/payment_prefs.h"
#include "components/permissions/permission_manager.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/in_memory_pref_store.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_service_factory.h"
#include "components/reduce_accept_language/browser/reduce_accept_language_service.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
#include "components/site_isolation/pref_names.h"
#include "components/site_isolation/site_isolation_policy.h"
#include "components/translate/core/browser/translate_pref_names.h"
#include "components/translate/core/browser/translate_prefs.h"
#include "components/user_prefs/user_prefs.h"
#include "components/variations/proto/study.pb.h"
#include "components/variations/variations.mojom.h"
#include "components/variations/variations_client.h"
#include "components/variations/variations_ids_provider.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/storage_partition.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "weblayer/browser/background_fetch/background_fetch_delegate_factory.h"
#include "weblayer/browser/background_fetch/background_fetch_delegate_impl.h"
#include "weblayer/browser/background_sync/background_sync_controller_factory.h"
#include "weblayer/browser/browsing_data_remover_delegate.h"
#include "weblayer/browser/browsing_data_remover_delegate_factory.h"
#include "weblayer/browser/client_hints_factory.h"
#include "weblayer/browser/heavy_ad_service_factory.h"
#include "weblayer/browser/origin_trials_factory.h"
#include "weblayer/browser/permissions/permission_manager_factory.h"
#include "weblayer/browser/reduce_accept_language_factory.h"
#include "weblayer/browser/stateful_ssl_host_state_delegate_factory.h"
#include "weblayer/public/common/switches.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/path_utils.h"
#include "components/browser_ui/accessibility/android/font_size_prefs_android.h"
#include "components/cdm/browser/media_drm_storage_impl.h" // nogncheck
#include "components/permissions/contexts/geolocation_permission_context_android.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "components/unified_consent/pref_names.h"
#elif BUILDFLAG(IS_WIN)
#include <windows.h>
#include <KnownFolders.h>
#include <shlobj.h>
#include "base/win/scoped_co_mem.h"
#elif BUILDFLAG(IS_POSIX)
#include "base/nix/xdg_util.h"
#endif
namespace weblayer {
namespace {
// Ignores origin security check. DownloadManagerImpl will provide its own
// implementation when InProgressDownloadManager object is passed to it.
bool IgnoreOriginSecurityCheck(const GURL& url) {
return true;
}
void BindWakeLockProvider(
mojo::PendingReceiver<device::mojom::WakeLockProvider> receiver) {
content::GetDeviceService().BindWakeLockProvider(std::move(receiver));
}
} // namespace
namespace prefs {
// Used to persist the public SettingType::NETWORK_PREDICTION_ENABLED API.
const char kNoStatePrefetchEnabled[] = "weblayer.network_prediction_enabled";
// Used to persist the public SettingType::UKM_ENABLED API.
const char kUkmEnabled[] = "weblayer.ukm_enabled";
} // namespace prefs
class ResourceContextImpl : public content::ResourceContext {
public:
ResourceContextImpl() = default;
ResourceContextImpl(const ResourceContextImpl&) = delete;
ResourceContextImpl& operator=(const ResourceContextImpl&) = delete;
~ResourceContextImpl() override = default;
};
BrowserContextImpl::BrowserContextImpl(ProfileImpl* profile_impl,
const base::FilePath& path)
: profile_impl_(profile_impl),
path_(path),
simple_factory_key_(path, path.empty()),
resource_context_(new ResourceContextImpl()),
download_delegate_(GetDownloadManager()) {
CreateUserPrefService();
BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
this);
auto* heavy_ad_service = HeavyAdServiceFactory::GetForBrowserContext(this);
if (IsOffTheRecord()) {
heavy_ad_service->InitializeOffTheRecord();
} else {
heavy_ad_service->Initialize(GetPath());
}
site_isolation::SiteIsolationPolicy::ApplyPersistedIsolatedOrigins(this);
// Ensure the delegate is initialized early to give it time to load its
// persistence.
GetOriginTrialsControllerDelegate();
}
BrowserContextImpl::~BrowserContextImpl() {
BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
this);
}
base::FilePath BrowserContextImpl::GetDefaultDownloadDirectory() {
// Note: if we wanted to productionize this on Windows/Linux, refactor
// src/chrome's GetDefaultDownloadDirectory.
base::FilePath download_dir;
#if BUILDFLAG(IS_ANDROID)
base::android::GetDownloadsDirectory(&download_dir);
#elif BUILDFLAG(IS_WIN)
base::win::ScopedCoMem<wchar_t> path_buf;
if (SUCCEEDED(
SHGetKnownFolderPath(FOLDERID_Downloads, 0, nullptr, &path_buf))) {
download_dir = base::FilePath(path_buf.get());
}
#else
download_dir = base::nix::GetXDGUserDirectory("DOWNLOAD", "Downloads");
#endif
return download_dir;
}
std::unique_ptr<content::ZoomLevelDelegate>
BrowserContextImpl::CreateZoomLevelDelegate(const base::FilePath&) {
return nullptr;
}
base::FilePath BrowserContextImpl::GetPath() {
return path_;
}
bool BrowserContextImpl::IsOffTheRecord() {
return path_.empty();
}
content::DownloadManagerDelegate*
BrowserContextImpl::GetDownloadManagerDelegate() {
return &download_delegate_;
}
content::ResourceContext* BrowserContextImpl::GetResourceContext() {
return resource_context_.get();
}
content::BrowserPluginGuestManager* BrowserContextImpl::GetGuestManager() {
return nullptr;
}
storage::SpecialStoragePolicy* BrowserContextImpl::GetSpecialStoragePolicy() {
return nullptr;
}
content::PlatformNotificationService*
BrowserContextImpl::GetPlatformNotificationService() {
return nullptr;
}
content::PushMessagingService* BrowserContextImpl::GetPushMessagingService() {
return nullptr;
}
content::StorageNotificationService*
BrowserContextImpl::GetStorageNotificationService() {
return nullptr;
}
content::SSLHostStateDelegate* BrowserContextImpl::GetSSLHostStateDelegate() {
return StatefulSSLHostStateDelegateFactory::GetForBrowserContext(this);
}
content::PermissionControllerDelegate*
BrowserContextImpl::GetPermissionControllerDelegate() {
return PermissionManagerFactory::GetForBrowserContext(this);
}
content::ClientHintsControllerDelegate*
BrowserContextImpl::GetClientHintsControllerDelegate() {
return ClientHintsFactory::GetForBrowserContext(this);
}
content::BackgroundFetchDelegate*
BrowserContextImpl::GetBackgroundFetchDelegate() {
return BackgroundFetchDelegateFactory::GetForBrowserContext(this);
}
content::BackgroundSyncController*
BrowserContextImpl::GetBackgroundSyncController() {
return BackgroundSyncControllerFactory::GetForBrowserContext(this);
}
content::BrowsingDataRemoverDelegate*
BrowserContextImpl::GetBrowsingDataRemoverDelegate() {
return BrowsingDataRemoverDelegateFactory::GetForBrowserContext(this);
}
content::ReduceAcceptLanguageControllerDelegate*
BrowserContextImpl::GetReduceAcceptLanguageControllerDelegate() {
return ReduceAcceptLanguageFactory::GetForBrowserContext(this);
}
content::OriginTrialsControllerDelegate*
BrowserContextImpl::GetOriginTrialsControllerDelegate() {
return OriginTrialsFactory::GetForBrowserContext(this);
}
std::unique_ptr<download::InProgressDownloadManager>
BrowserContextImpl::RetrieveInProgressDownloadManager() {
// Override this to provide a connection to the wake lock service.
auto download_manager = std::make_unique<download::InProgressDownloadManager>(
nullptr, path_,
path_.empty() ? nullptr
: GetDefaultStoragePartition()->GetProtoDatabaseProvider(),
base::BindRepeating(&IgnoreOriginSecurityCheck),
base::BindRepeating(&content::DownloadRequestUtils::IsURLSafe),
base::BindRepeating(&BindWakeLockProvider));
#if BUILDFLAG(IS_ANDROID)
download_manager->set_default_download_dir(GetDefaultDownloadDirectory());
#endif
return download_manager;
}
content::ContentIndexProvider* BrowserContextImpl::GetContentIndexProvider() {
return nullptr;
}
void BrowserContextImpl::CreateUserPrefService() {
auto pref_registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>();
RegisterPrefs(pref_registry.get());
PrefServiceFactory pref_service_factory;
if (IsOffTheRecord()) {
pref_service_factory.set_user_prefs(
base::MakeRefCounted<InMemoryPrefStore>());
} else {
pref_service_factory.set_user_prefs(base::MakeRefCounted<JsonPrefStore>(
path_.Append(FILE_PATH_LITERAL("Preferences"))));
}
{
// Creating the prefs service may require reading the preferences from disk.
base::ScopedAllowBlocking allow_io;
user_pref_service_ = pref_service_factory.Create(pref_registry);
}
// Note: UserPrefs::Set also ensures that the user_pref_service_ has not
// been set previously.
user_prefs::UserPrefs::Set(this, user_pref_service_.get());
}
void BrowserContextImpl::RegisterPrefs(
user_prefs::PrefRegistrySyncable* pref_registry) {
pref_registry->RegisterBooleanPref(prefs::kNoStatePrefetchEnabled, true);
pref_registry->RegisterBooleanPref(prefs::kUkmEnabled, false);
// This pref is used by captive_portal::CaptivePortalService (as well as other
// potential use cases in the future, as it is used for various purposes
// through //chrome).
pref_registry->RegisterBooleanPref(
embedder_support::kAlternateErrorPagesEnabled, true);
pref_registry->RegisterListPref(
site_isolation::prefs::kUserTriggeredIsolatedOrigins);
pref_registry->RegisterDictionaryPref(
site_isolation::prefs::kWebTriggeredIsolatedOrigins);
StatefulSSLHostStateDelegate::RegisterProfilePrefs(pref_registry);
HostContentSettingsMap::RegisterProfilePrefs(pref_registry);
safe_browsing::RegisterProfilePrefs(pref_registry);
language::LanguagePrefs::RegisterProfilePrefs(pref_registry);
translate::TranslatePrefs::RegisterProfilePrefs(pref_registry);
blocked_content::SafeBrowsingTriggeredPopupBlocker::RegisterProfilePrefs(
pref_registry);
payments::RegisterProfilePrefs(pref_registry);
pref_registry->RegisterBooleanPref(
translate::prefs::kOfferTranslateEnabled, true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#if BUILDFLAG(IS_ANDROID)
site_engagement::SiteEngagementService::RegisterProfilePrefs(pref_registry);
cdm::MediaDrmStorageImpl::RegisterProfilePrefs(pref_registry);
permissions::GeolocationPermissionContextAndroid::RegisterProfilePrefs(
pref_registry);
pref_registry->RegisterBooleanPref(
unified_consent::prefs::kUrlKeyedAnonymizedDataCollectionEnabled, false);
pref_registry->RegisterDoublePref(browser_ui::prefs::kWebKitFontScaleFactor,
1.0);
blink::web_pref::WebPreferences pref_defaults;
pref_registry->RegisterBooleanPref(browser_ui::prefs::kWebKitForceEnableZoom,
pref_defaults.force_enable_zoom);
pref_registry->SetDefaultPrefValue(::prefs::kSafeBrowsingEnhanced,
base::Value(true));
#endif
BrowserContextDependencyManager::GetInstance()
->RegisterProfilePrefsForServices(pref_registry);
}
class BrowserContextImpl::WebLayerVariationsClient
: public variations::VariationsClient {
public:
explicit WebLayerVariationsClient(content::BrowserContext* browser_context)
: browser_context_(browser_context) {}
~WebLayerVariationsClient() override = default;
bool IsOffTheRecord() const override {
return browser_context_->IsOffTheRecord();
}
variations::mojom::VariationsHeadersPtr GetVariationsHeaders()
const override {
// As the embedder supplies the set of ids, the signed-in state should be
// ignored. The value supplied (`is_signed_in`) doesn't matter as
// VariationsIdsProvider is configured to ignore the signed in state.
const bool is_signed_in = true;
DCHECK_EQ(variations::VariationsIdsProvider::Mode::kIgnoreSignedInState,
variations::VariationsIdsProvider::GetInstance()->mode());
return variations::VariationsIdsProvider::GetInstance()
->GetClientDataHeaders(is_signed_in);
}
private:
raw_ptr<content::BrowserContext> browser_context_;
};
variations::VariationsClient* BrowserContextImpl::GetVariationsClient() {
if (!weblayer_variations_client_) {
weblayer_variations_client_ =
std::make_unique<WebLayerVariationsClient>(this);
}
return weblayer_variations_client_.get();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_context_impl.cc | C++ | unknown | 14,047 |
// 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_BROWSER_CONTEXT_IMPL_H_
#define WEBLAYER_BROWSER_BROWSER_CONTEXT_IMPL_H_
#include "base/files/file_path.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "components/keyed_service/core/simple_factory_key.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "weblayer/browser/download_manager_delegate_impl.h"
#include "weblayer/public/profile.h"
namespace user_prefs {
class PrefRegistrySyncable;
}
class PrefService;
namespace weblayer {
class ProfileImpl;
class ResourceContextImpl;
namespace prefs {
// WebLayer specific pref names.
extern const char kNoStatePrefetchEnabled[];
extern const char kUkmEnabled[];
} // namespace prefs
class BrowserContextImpl : public content::BrowserContext {
public:
BrowserContextImpl(ProfileImpl* profile_impl, const base::FilePath& path);
~BrowserContextImpl() override;
BrowserContextImpl(const BrowserContextImpl&) = delete;
BrowserContextImpl& operator=(const BrowserContextImpl&) = delete;
static base::FilePath GetDefaultDownloadDirectory();
// BrowserContext implementation:
std::unique_ptr<content::ZoomLevelDelegate> CreateZoomLevelDelegate(
const base::FilePath&) override;
base::FilePath GetPath() override;
bool IsOffTheRecord() override;
variations::VariationsClient* GetVariationsClient() override;
content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
content::ResourceContext* GetResourceContext() override;
content::BrowserPluginGuestManager* GetGuestManager() override;
storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override;
content::PlatformNotificationService* GetPlatformNotificationService()
override;
content::PushMessagingService* GetPushMessagingService() override;
content::StorageNotificationService* GetStorageNotificationService() override;
content::SSLHostStateDelegate* GetSSLHostStateDelegate() override;
content::PermissionControllerDelegate* GetPermissionControllerDelegate()
override;
content::ClientHintsControllerDelegate* GetClientHintsControllerDelegate()
override;
content::BackgroundFetchDelegate* GetBackgroundFetchDelegate() override;
content::BackgroundSyncController* GetBackgroundSyncController() override;
content::BrowsingDataRemoverDelegate* GetBrowsingDataRemoverDelegate()
override;
std::unique_ptr<download::InProgressDownloadManager>
RetrieveInProgressDownloadManager() override;
content::ContentIndexProvider* GetContentIndexProvider() override;
content::ReduceAcceptLanguageControllerDelegate*
GetReduceAcceptLanguageControllerDelegate() override;
content::OriginTrialsControllerDelegate* GetOriginTrialsControllerDelegate()
override;
ProfileImpl* profile_impl() const { return profile_impl_; }
PrefService* pref_service() const { return user_pref_service_.get(); }
SimpleFactoryKey* simple_factory_key() { return &simple_factory_key_; }
private:
class WebLayerVariationsClient;
// Creates a simple in-memory pref service.
// TODO(timvolodine): Investigate whether WebLayer needs persistent pref
// service.
void CreateUserPrefService();
// Registers the preferences that WebLayer accesses.
void RegisterPrefs(user_prefs::PrefRegistrySyncable* pref_registry);
const raw_ptr<ProfileImpl> profile_impl_;
base::FilePath path_;
// In Chrome, a SimpleFactoryKey is used as a minimal representation of a
// BrowserContext used before full browser mode has started. WebLayer doesn't
// have an incomplete mode, so this is just a member variable for
// compatibility with components that expect a SimpleFactoryKey.
SimpleFactoryKey simple_factory_key_;
// ResourceContext needs to be deleted on the IO thread in general (and in
// particular due to the destruction of the safebrowsing mojo interface
// that has been added in ContentBrowserClient::ExposeInterfacesToRenderer
// on IO thread, see crbug.com/1029317). Also this is similar to how Chrome
// handles ProfileIOData.
// TODO(timvolodine): consider a more general Profile shutdown/destruction
// sequence for the IO/UI bits (crbug.com/1029879).
std::unique_ptr<ResourceContextImpl, content::BrowserThread::DeleteOnIOThread>
resource_context_;
DownloadManagerDelegateImpl download_delegate_;
std::unique_ptr<PrefService> user_pref_service_;
std::unique_ptr<WebLayerVariationsClient> weblayer_variations_client_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSER_CONTEXT_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_context_impl.h | C++ | unknown | 4,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.
#include "weblayer/browser/browser_impl.h"
#include "base/containers/unique_ptr_adapters.h"
#include "base/memory/ptr_util.h"
#include "base/path_service.h"
#include "base/ranges/algorithm.h"
#include "build/build_config.h"
#include "components/base32/base32.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_list.h"
#include "weblayer/browser/feature_list_creator.h"
#include "weblayer/browser/persistence/browser_persister.h"
#include "weblayer/browser/persistence/browser_persister_file_utils.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/common/weblayer_paths.h"
#include "weblayer/public/browser_observer.h"
#include "weblayer/public/browser_restore_observer.h"
#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 "components/browser_ui/accessibility/android/font_size_prefs_android.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/java/jni/BrowserImpl_jni.h"
using base::android::AttachCurrentThread;
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
#endif
namespace weblayer {
#if BUILDFLAG(IS_ANDROID)
// This MUST match the values defined in
// org.chromium.weblayer_private.interfaces.DarkModeStrategy.
enum class DarkModeStrategy {
kWebThemeDarkeningOnly = 0,
kUserAgentDarkeningOnly = 1,
kPreferWebThemeOverUserAgentDarkening = 2,
};
#endif
// static
constexpr char BrowserImpl::kPersistenceFilePrefix[];
std::unique_ptr<Browser> Browser::Create(
Profile* profile,
const PersistenceInfo* persistence_info) {
// BrowserImpl's constructor is private.
auto browser =
base::WrapUnique(new BrowserImpl(static_cast<ProfileImpl*>(profile)));
if (persistence_info)
browser->RestoreStateIfNecessary(*persistence_info);
return browser;
}
BrowserImpl::~BrowserImpl() {
#if BUILDFLAG(IS_ANDROID)
// Android side should always remove tabs first (because the Java Tab class
// owns the C++ Tab). See BrowserImpl.destroy() (in the Java BrowserImpl
// class).
DCHECK(tabs_.empty());
#else
while (!tabs_.empty())
DestroyTab(tabs_.back().get());
#endif
BrowserList::GetInstance()->RemoveBrowser(this);
#if BUILDFLAG(IS_ANDROID)
if (BrowserList::GetInstance()->browsers().empty())
BrowserProcess::GetInstance()->StopSafeBrowsingService();
#endif
}
TabImpl* BrowserImpl::CreateTabForSessionRestore(
std::unique_ptr<content::WebContents> web_contents,
const std::string& guid) {
if (!web_contents) {
content::WebContents::CreateParams create_params(
profile_->GetBrowserContext());
web_contents = content::WebContents::Create(create_params);
}
std::unique_ptr<TabImpl> tab =
std::make_unique<TabImpl>(profile_, std::move(web_contents), guid);
#if BUILDFLAG(IS_ANDROID)
Java_BrowserImpl_createJavaTabForNativeTab(
AttachCurrentThread(), java_impl_, reinterpret_cast<jlong>(tab.get()));
#endif
return AddTab(std::move(tab));
}
TabImpl* BrowserImpl::CreateTab(
std::unique_ptr<content::WebContents> web_contents) {
return CreateTabForSessionRestore(std::move(web_contents), std::string());
}
#if BUILDFLAG(IS_ANDROID)
bool BrowserImpl::CompositorHasSurface() {
return Java_BrowserImpl_compositorHasSurface(AttachCurrentThread(),
java_impl_);
}
void BrowserImpl::AddTab(JNIEnv* env, long native_tab) {
AddTab(reinterpret_cast<TabImpl*>(native_tab));
}
ScopedJavaLocalRef<jobjectArray> BrowserImpl::GetTabs(JNIEnv* env) {
ScopedJavaLocalRef<jclass> clazz =
base::android::GetClass(env, "org/chromium/weblayer_private/TabImpl");
jobjectArray tabs = env->NewObjectArray(tabs_.size(), clazz.obj(),
nullptr /* initialElement */);
base::android::CheckException(env);
for (size_t i = 0; i < tabs_.size(); ++i) {
TabImpl* tab = static_cast<TabImpl*>(tabs_[i].get());
env->SetObjectArrayElement(tabs, i, tab->GetJavaTab().obj());
}
return ScopedJavaLocalRef<jobjectArray>(env, tabs);
}
void BrowserImpl::SetActiveTab(JNIEnv* env, long native_tab) {
SetActiveTab(reinterpret_cast<TabImpl*>(native_tab));
}
ScopedJavaLocalRef<jobject> BrowserImpl::GetActiveTab(JNIEnv* env) {
if (!active_tab_)
return nullptr;
return ScopedJavaLocalRef<jobject>(active_tab_->GetJavaTab());
}
void BrowserImpl::PrepareForShutdown(JNIEnv* env) {
PrepareForShutdown();
}
void BrowserImpl::RestoreStateIfNecessary(
JNIEnv* env,
const JavaParamRef<jstring>& j_persistence_id) {
if (!j_persistence_id.obj())
return;
Browser::PersistenceInfo persistence_info;
persistence_info.id =
base::android::ConvertJavaStringToUTF8(j_persistence_id);
if (persistence_info.id.empty())
return;
RestoreStateIfNecessary(persistence_info);
}
void BrowserImpl::WebPreferencesChanged(JNIEnv* env) {
OnWebPreferenceChanged(std::string());
}
void BrowserImpl::OnFragmentStart(JNIEnv* env) {
// FeatureListCreator is created before any Browsers.
DCHECK(FeatureListCreator::GetInstance());
FeatureListCreator::GetInstance()->OnBrowserFragmentStarted();
}
void BrowserImpl::OnFragmentResume(JNIEnv* env) {
UpdateFragmentResumedState(true);
}
void BrowserImpl::OnFragmentPause(JNIEnv* env) {
UpdateFragmentResumedState(false);
}
#endif
void BrowserImpl::SetWebPreferences(blink::web_pref::WebPreferences* prefs) {
#if BUILDFLAG(IS_ANDROID)
PrefService* pref_service = profile()->GetBrowserContext()->pref_service();
prefs->password_echo_enabled = Java_BrowserImpl_getPasswordEchoEnabled(
AttachCurrentThread(), java_impl_);
prefs->font_scale_factor = static_cast<float>(
pref_service->GetDouble(browser_ui::prefs::kWebKitFontScaleFactor));
prefs->force_enable_zoom =
pref_service->GetBoolean(browser_ui::prefs::kWebKitForceEnableZoom);
bool is_dark =
Java_BrowserImpl_getDarkThemeEnabled(AttachCurrentThread(), java_impl_);
if (is_dark) {
DarkModeStrategy dark_strategy =
static_cast<DarkModeStrategy>(Java_BrowserImpl_getDarkModeStrategy(
AttachCurrentThread(), java_impl_));
switch (dark_strategy) {
case DarkModeStrategy::kPreferWebThemeOverUserAgentDarkening:
// Blink's behavior is that if the preferred color scheme matches the
// browser's color scheme, then force dark will be disabled, otherwise
// the preferred color scheme will be reset to 'light'. Therefore
// when enabling force dark, we also set the preferred color scheme to
// dark so that dark themed content will be preferred over force
// darkening.
prefs->preferred_color_scheme =
blink::mojom::PreferredColorScheme::kDark;
prefs->force_dark_mode_enabled = true;
break;
case DarkModeStrategy::kWebThemeDarkeningOnly:
prefs->preferred_color_scheme =
blink::mojom::PreferredColorScheme::kDark;
prefs->force_dark_mode_enabled = false;
break;
case DarkModeStrategy::kUserAgentDarkeningOnly:
prefs->preferred_color_scheme =
blink::mojom::PreferredColorScheme::kLight;
prefs->force_dark_mode_enabled = true;
break;
}
} else {
prefs->preferred_color_scheme = blink::mojom::PreferredColorScheme::kLight;
prefs->force_dark_mode_enabled = false;
}
#endif
}
#if BUILDFLAG(IS_ANDROID)
void BrowserImpl::RemoveTabBeforeDestroyingFromJava(Tab* tab) {
// The java side owns the Tab, and is going to delete it shortly. See
// JNI_TabImpl_DeleteTab.
RemoveTab(tab).release();
}
#endif
void BrowserImpl::AddTab(Tab* tab) {
DCHECK(tab);
TabImpl* tab_impl = static_cast<TabImpl*>(tab);
std::unique_ptr<Tab> owned_tab;
if (tab_impl->browser())
owned_tab = tab_impl->browser()->RemoveTab(tab_impl);
else
owned_tab.reset(tab_impl);
AddTab(std::move(owned_tab));
}
void BrowserImpl::DestroyTab(Tab* tab) {
#if BUILDFLAG(IS_ANDROID)
// Route destruction through the java side.
Java_BrowserImpl_destroyTabImpl(AttachCurrentThread(), java_impl_,
static_cast<TabImpl*>(tab)->GetJavaTab());
#else
RemoveTab(tab);
#endif
}
void BrowserImpl::SetActiveTab(Tab* tab) {
if (GetActiveTab() == tab)
return;
if (active_tab_)
active_tab_->OnLosingActive();
// TODO: currently the java side sets visibility, this code likely should
// too and it should be removed from the java side.
active_tab_ = static_cast<TabImpl*>(tab);
#if BUILDFLAG(IS_ANDROID)
Java_BrowserImpl_onActiveTabChanged(
AttachCurrentThread(), java_impl_,
active_tab_ ? active_tab_->GetJavaTab() : nullptr);
#endif
VisibleSecurityStateOfActiveTabChanged();
for (BrowserObserver& obs : browser_observers_)
obs.OnActiveTabChanged(active_tab_);
if (active_tab_)
active_tab_->OnGainedActive();
}
Tab* BrowserImpl::GetActiveTab() {
return active_tab_;
}
std::vector<Tab*> BrowserImpl::GetTabs() {
std::vector<Tab*> tabs(tabs_.size());
for (size_t i = 0; i < tabs_.size(); ++i)
tabs[i] = tabs_[i].get();
return tabs;
}
Tab* BrowserImpl::CreateTab() {
return CreateTab(nullptr);
}
void BrowserImpl::OnRestoreCompleted() {
for (BrowserRestoreObserver& obs : browser_restore_observers_)
obs.OnRestoreCompleted();
#if BUILDFLAG(IS_ANDROID)
Java_BrowserImpl_onRestoreCompleted(AttachCurrentThread(), java_impl_);
#endif
}
void BrowserImpl::PrepareForShutdown() {
browser_persister_.reset();
}
std::string BrowserImpl::GetPersistenceId() {
return persistence_id_;
}
bool BrowserImpl::IsRestoringPreviousState() {
return browser_persister_ && browser_persister_->is_restore_in_progress();
}
void BrowserImpl::AddObserver(BrowserObserver* observer) {
browser_observers_.AddObserver(observer);
}
void BrowserImpl::RemoveObserver(BrowserObserver* observer) {
browser_observers_.RemoveObserver(observer);
}
void BrowserImpl::AddBrowserRestoreObserver(BrowserRestoreObserver* observer) {
browser_restore_observers_.AddObserver(observer);
}
void BrowserImpl::RemoveBrowserRestoreObserver(
BrowserRestoreObserver* observer) {
browser_restore_observers_.RemoveObserver(observer);
}
void BrowserImpl::VisibleSecurityStateOfActiveTabChanged() {
if (visible_security_state_changed_callback_for_tests_)
std::move(visible_security_state_changed_callback_for_tests_).Run();
#if BUILDFLAG(IS_ANDROID)
JNIEnv* env = base::android::AttachCurrentThread();
Java_BrowserImpl_onVisibleSecurityStateOfActiveTabChanged(env, java_impl_);
#endif
}
BrowserImpl::BrowserImpl(ProfileImpl* profile) : profile_(profile) {
BrowserList::GetInstance()->AddBrowser(this);
#if BUILDFLAG(IS_ANDROID)
profile_pref_change_registrar_.Init(
profile_->GetBrowserContext()->pref_service());
auto pref_change_callback = base::BindRepeating(
&BrowserImpl::OnWebPreferenceChanged, base::Unretained(this));
profile_pref_change_registrar_.Add(browser_ui::prefs::kWebKitFontScaleFactor,
pref_change_callback);
profile_pref_change_registrar_.Add(browser_ui::prefs::kWebKitForceEnableZoom,
pref_change_callback);
#endif
}
void BrowserImpl::RestoreStateIfNecessary(
const PersistenceInfo& persistence_info) {
persistence_id_ = persistence_info.id;
if (!persistence_id_.empty()) {
browser_persister_ =
std::make_unique<BrowserPersister>(GetBrowserPersisterDataPath(), this);
}
}
TabImpl* BrowserImpl::AddTab(std::unique_ptr<Tab> tab) {
TabImpl* tab_impl = static_cast<TabImpl*>(tab.get());
DCHECK(!tab_impl->browser());
tabs_.push_back(std::move(tab));
tab_impl->set_browser(this);
#if BUILDFLAG(IS_ANDROID)
Java_BrowserImpl_onTabAdded(AttachCurrentThread(), java_impl_,
tab_impl->GetJavaTab());
#endif
for (BrowserObserver& obs : browser_observers_)
obs.OnTabAdded(tab_impl);
return tab_impl;
}
std::unique_ptr<Tab> BrowserImpl::RemoveTab(Tab* tab) {
TabImpl* tab_impl = static_cast<TabImpl*>(tab);
DCHECK_EQ(this, tab_impl->browser());
static_cast<TabImpl*>(tab)->set_browser(nullptr);
auto iter = base::ranges::find_if(tabs_, base::MatchesUniquePtr(tab));
DCHECK(iter != tabs_.end());
std::unique_ptr<Tab> owned_tab = std::move(*iter);
tabs_.erase(iter);
const bool active_tab_changed = active_tab_ == tab;
if (active_tab_changed)
SetActiveTab(nullptr);
#if BUILDFLAG(IS_ANDROID)
Java_BrowserImpl_onTabRemoved(AttachCurrentThread(), java_impl_,
tab ? tab_impl->GetJavaTab() : nullptr);
#endif
for (BrowserObserver& obs : browser_observers_)
obs.OnTabRemoved(tab, active_tab_changed);
return owned_tab;
}
base::FilePath BrowserImpl::GetBrowserPersisterDataPath() {
return BuildBasePathForBrowserPersister(
profile_->GetBrowserPersisterDataBaseDir(), GetPersistenceId());
}
void BrowserImpl::OnWebPreferenceChanged(const std::string& pref_name) {
for (const auto& tab : tabs_) {
TabImpl* tab_impl = static_cast<TabImpl*>(tab.get());
tab_impl->WebPreferencesChanged();
}
}
#if BUILDFLAG(IS_ANDROID)
void BrowserImpl::UpdateFragmentResumedState(bool state) {
const bool old_has_at_least_one_active_browser =
BrowserList::GetInstance()->HasAtLeastOneResumedBrowser();
fragment_resumed_ = state;
if (old_has_at_least_one_active_browser !=
BrowserList::GetInstance()->HasAtLeastOneResumedBrowser()) {
BrowserList::GetInstance()->NotifyHasAtLeastOneResumedBrowserChanged();
}
}
// This function is friended. JNI_BrowserImpl_CreateBrowser can not be
// friended, as it requires browser_impl.h to include BrowserImpl_jni.h, which
// is problematic (meaning not really supported and generates compile errors).
BrowserImpl* CreateBrowserForAndroid(ProfileImpl* profile,
const std::string& package_name,
const JavaParamRef<jobject>& java_impl) {
BrowserImpl* browser = new BrowserImpl(profile);
browser->java_impl_ = java_impl;
browser->package_name_ = package_name;
return browser;
}
static jlong JNI_BrowserImpl_CreateBrowser(
JNIEnv* env,
jlong profile,
const base::android::JavaParamRef<jstring>& package_name,
const JavaParamRef<jobject>& java_impl) {
// The android side does not trigger restore from the constructor as at the
// time this is called not enough of WebLayer has been wired up. Specifically,
// when this is called BrowserImpl.java hasn't obtained the return value so
// that it can't call any functions and further the client side hasn't been
// fully created, leading to all sort of assertions if Tabs are created
// and/or navigations start (which restore may trigger).
return reinterpret_cast<intptr_t>(CreateBrowserForAndroid(
reinterpret_cast<ProfileImpl*>(profile),
base::android::ConvertJavaStringToUTF8(env, package_name), java_impl));
}
static void JNI_BrowserImpl_DeleteBrowser(JNIEnv* env, jlong browser) {
delete reinterpret_cast<BrowserImpl*>(browser);
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_impl.cc | C++ | unknown | 15,527 |
// 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_BROWSER_IMPL_H_
#define WEBLAYER_BROWSER_BROWSER_IMPL_H_
#include <memory>
#include <vector>
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "build/build_config.h"
#include "components/prefs/pref_change_registrar.h"
#include "weblayer/public/browser.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/scoped_java_ref.h"
#endif
namespace base {
class FilePath;
}
namespace blink {
namespace web_pref {
struct WebPreferences;
}
} // namespace blink
namespace content {
class WebContents;
}
namespace weblayer {
class BrowserPersister;
class ProfileImpl;
class TabImpl;
class BrowserImpl : public Browser {
public:
// Prefix used for storing persistence state.
static constexpr char kPersistenceFilePrefix[] = "State";
BrowserImpl(const BrowserImpl&) = delete;
BrowserImpl& operator=(const BrowserImpl&) = delete;
~BrowserImpl() override;
BrowserPersister* browser_persister() { return browser_persister_.get(); }
ProfileImpl* profile() { return profile_; }
// Creates and adds a Tab from session restore. The returned tab is owned by
// this Browser.
TabImpl* CreateTabForSessionRestore(
std::unique_ptr<content::WebContents> web_contents,
const std::string& guid);
TabImpl* CreateTab(std::unique_ptr<content::WebContents> web_contents);
// Called from BrowserPersister when restore has completed.
void OnRestoreCompleted();
const std::string& GetPackageName() { return package_name_; }
#if BUILDFLAG(IS_ANDROID)
bool CompositorHasSurface();
base::android::ScopedJavaGlobalRef<jobject> java_browser() {
return java_impl_;
}
void AddTab(JNIEnv* env, long native_tab);
base::android::ScopedJavaLocalRef<jobjectArray> GetTabs(JNIEnv* env);
void SetActiveTab(JNIEnv* env, long native_tab);
base::android::ScopedJavaLocalRef<jobject> GetActiveTab(JNIEnv* env);
void PrepareForShutdown(JNIEnv* env);
base::android::ScopedJavaLocalRef<jstring> GetPersistenceId(JNIEnv* env);
void SaveBrowserPersisterIfNecessary(JNIEnv* env);
base::android::ScopedJavaLocalRef<jbyteArray> GetMinimalPersistenceState(
JNIEnv* env,
int max_navigations_per_tab);
void RestoreStateIfNecessary(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& j_persistence_id);
void WebPreferencesChanged(JNIEnv* env);
void OnFragmentStart(JNIEnv* env);
void OnFragmentResume(JNIEnv* env);
void OnFragmentPause(JNIEnv* env);
bool IsRestoringPreviousState(JNIEnv* env) {
return IsRestoringPreviousState();
}
bool fragment_resumed() { return fragment_resumed_; }
#endif
// Used in tests to specify a non-default max (0 means use the default).
std::vector<uint8_t> GetMinimalPersistenceState(int max_navigations_per_tab,
int max_size_in_bytes);
// Used by tests to specify a callback to listen to changes to visible
// security state.
void set_visible_security_state_callback_for_tests(
base::OnceClosure closure) {
visible_security_state_changed_callback_for_tests_ = std::move(closure);
}
bool GetPasswordEchoEnabled();
void SetWebPreferences(blink::web_pref::WebPreferences* prefs);
#if BUILDFLAG(IS_ANDROID)
// On Android the Java Tab class owns the C++ Tab. DestroyTab() calls to the
// Java Tab class to initiate deletion. This function is called from the Java
// side to remove the tab from the browser and shortly followed by deleting
// the tab.
void RemoveTabBeforeDestroyingFromJava(Tab* tab);
#endif
// Browser:
void AddTab(Tab* tab) override;
void DestroyTab(Tab* tab) override;
void SetActiveTab(Tab* tab) override;
Tab* GetActiveTab() override;
std::vector<Tab*> GetTabs() override;
Tab* CreateTab() override;
void PrepareForShutdown() override;
std::string GetPersistenceId() override;
bool IsRestoringPreviousState() override;
void AddObserver(BrowserObserver* observer) override;
void RemoveObserver(BrowserObserver* observer) override;
void AddBrowserRestoreObserver(BrowserRestoreObserver* observer) override;
void RemoveBrowserRestoreObserver(BrowserRestoreObserver* observer) override;
void VisibleSecurityStateOfActiveTabChanged() override;
private:
// For creation.
friend class Browser;
#if BUILDFLAG(IS_ANDROID)
friend BrowserImpl* CreateBrowserForAndroid(
ProfileImpl*,
const std::string&,
const base::android::JavaParamRef<jobject>&);
#endif
explicit BrowserImpl(ProfileImpl* profile);
void RestoreStateIfNecessary(const PersistenceInfo& persistence_info);
TabImpl* AddTab(std::unique_ptr<Tab> tab);
std::unique_ptr<Tab> RemoveTab(Tab* tab);
// Returns the path used by |browser_persister_|.
base::FilePath GetBrowserPersisterDataPath();
void OnWebPreferenceChanged(const std::string& pref_name);
#if BUILDFLAG(IS_ANDROID)
void UpdateFragmentResumedState(bool state);
bool fragment_resumed_ = false;
base::android::ScopedJavaGlobalRef<jobject> java_impl_;
#endif
base::ObserverList<BrowserObserver> browser_observers_;
base::ObserverList<BrowserRestoreObserver> browser_restore_observers_;
const raw_ptr<ProfileImpl> profile_;
std::vector<std::unique_ptr<Tab>> tabs_;
raw_ptr<TabImpl> active_tab_ = nullptr;
std::string persistence_id_;
std::unique_ptr<BrowserPersister> browser_persister_;
base::OnceClosure visible_security_state_changed_callback_for_tests_;
PrefChangeRegistrar profile_pref_change_registrar_;
std::string package_name_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_impl.h | C++ | unknown | 5,761 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/browser_list.h"
#include <functional>
#include "base/no_destructor.h"
#include "base/ranges/algorithm.h"
#include "build/build_config.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/browser_list_observer.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/browser_list_proxy.h"
#endif
namespace weblayer {
// static
BrowserList* BrowserList::GetInstance() {
static base::NoDestructor<BrowserList> browser_list;
return browser_list.get();
}
#if BUILDFLAG(IS_ANDROID)
bool BrowserList::HasAtLeastOneResumedBrowser() {
return base::ranges::any_of(browsers_, &BrowserImpl::fragment_resumed);
}
#endif
void BrowserList::AddObserver(BrowserListObserver* observer) {
observers_.AddObserver(observer);
}
void BrowserList::RemoveObserver(BrowserListObserver* observer) {
observers_.RemoveObserver(observer);
}
BrowserList::BrowserList() {
#if BUILDFLAG(IS_ANDROID)
browser_list_proxy_ = std::make_unique<BrowserListProxy>();
AddObserver(browser_list_proxy_.get());
#endif
}
BrowserList::~BrowserList() {
#if BUILDFLAG(IS_ANDROID)
RemoveObserver(browser_list_proxy_.get());
#endif
}
void BrowserList::AddBrowser(BrowserImpl* browser) {
DCHECK(!browsers_.contains(browser));
#if BUILDFLAG(IS_ANDROID)
// Browsers should not start out resumed.
DCHECK(!browser->fragment_resumed());
#endif
browsers_.insert(browser);
for (BrowserListObserver& observer : observers_)
observer.OnBrowserCreated(browser);
}
void BrowserList::RemoveBrowser(BrowserImpl* browser) {
DCHECK(browsers_.contains(browser));
#if BUILDFLAG(IS_ANDROID)
// Browsers should not be resumed when being destroyed.
DCHECK(!browser->fragment_resumed());
#endif
browsers_.erase(browser);
for (BrowserListObserver& observer : observers_)
observer.OnBrowserDestroyed(browser);
}
#if BUILDFLAG(IS_ANDROID)
void BrowserList::NotifyHasAtLeastOneResumedBrowserChanged() {
const bool value = HasAtLeastOneResumedBrowser();
for (BrowserListObserver& observer : observers_)
observer.OnHasAtLeastOneResumedBrowserStateChanged(value);
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_list.cc | C++ | unknown | 2,274 |
// 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_BROWSER_LIST_H_
#define WEBLAYER_BROWSER_BROWSER_LIST_H_
#include "base/containers/flat_set.h"
#include "base/no_destructor.h"
#include "base/observer_list.h"
#include "build/build_config.h"
namespace weblayer {
class BrowserImpl;
class BrowserListObserver;
#if BUILDFLAG(IS_ANDROID)
class BrowserListProxy;
#endif
// Tracks the set of browsers.
class BrowserList {
public:
BrowserList(const BrowserList&) = delete;
BrowserList& operator=(const BrowserList&) = delete;
static BrowserList* GetInstance();
const base::flat_set<BrowserImpl*>& browsers() { return browsers_; }
#if BUILDFLAG(IS_ANDROID)
// Returns true if there is at least one Browser in a resumed state.
bool HasAtLeastOneResumedBrowser();
#endif
void AddObserver(BrowserListObserver* observer);
void RemoveObserver(BrowserListObserver* observer);
private:
friend class BrowserImpl;
friend class base::NoDestructor<BrowserList>;
BrowserList();
~BrowserList();
void AddBrowser(BrowserImpl* browser);
void RemoveBrowser(BrowserImpl* browser);
#if BUILDFLAG(IS_ANDROID)
void NotifyHasAtLeastOneResumedBrowserChanged();
#endif
base::flat_set<BrowserImpl*> browsers_;
base::ObserverList<BrowserListObserver> observers_;
#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<BrowserListProxy> browser_list_proxy_;
#endif
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSER_LIST_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_list.h | C++ | unknown | 1,562 |
// 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_BROWSER_LIST_OBSERVER_H_
#define WEBLAYER_BROWSER_BROWSER_LIST_OBSERVER_H_
#include "base/observer_list_types.h"
#include "build/build_config.h"
namespace weblayer {
class Browser;
class BrowserListObserver : public base::CheckedObserver {
public:
#if BUILDFLAG(IS_ANDROID)
// Called when the value of BrowserList::HasAtLeastOneResumedBrowser()
// changes.
virtual void OnHasAtLeastOneResumedBrowserStateChanged(bool new_value) {}
#endif
virtual void OnBrowserCreated(Browser* browser) {}
virtual void OnBrowserDestroyed(Browser* browser) {}
protected:
~BrowserListObserver() override = default;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSER_LIST_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_list_observer.h | C++ | unknown | 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/browser_list_proxy.h"
#include "base/android/jni_android.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/browser_list.h"
#include "weblayer/browser/java/jni/BrowserList_jni.h"
namespace weblayer {
BrowserListProxy::BrowserListProxy()
: java_browser_list_(Java_BrowserList_createBrowserList(
base::android::AttachCurrentThread())) {}
BrowserListProxy::~BrowserListProxy() = default;
void BrowserListProxy::OnBrowserCreated(Browser* browser) {
Java_BrowserList_onBrowserCreated(
base::android::AttachCurrentThread(), java_browser_list_,
static_cast<BrowserImpl*>(browser)->java_browser());
}
void BrowserListProxy::OnBrowserDestroyed(Browser* browser) {
Java_BrowserList_onBrowserDestroyed(
base::android::AttachCurrentThread(), java_browser_list_,
static_cast<BrowserImpl*>(browser)->java_browser());
}
static void JNI_BrowserList_CreateBrowserList(JNIEnv* env) {
BrowserList::GetInstance();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_list_proxy.cc | C++ | unknown | 1,166 |
// 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_BROWSER_LIST_PROXY_H_
#define WEBLAYER_BROWSER_BROWSER_LIST_PROXY_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "weblayer/browser/browser_list_observer.h"
namespace weblayer {
// Owns the Java BrowserList implementation and funnels all BrowserListObserver
// calls to the java side.
class BrowserListProxy : public BrowserListObserver {
public:
BrowserListProxy();
BrowserListProxy(const BrowserListProxy&) = delete;
BrowserListProxy& operator=(const BrowserListProxy&) = delete;
~BrowserListProxy() override;
// BrowserListObserver:
void OnBrowserCreated(Browser* browser) override;
void OnBrowserDestroyed(Browser* browser) override;
private:
base::android::ScopedJavaGlobalRef<jobject> java_browser_list_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSER_LIST_PROXY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_list_proxy.h | C++ | unknown | 1,007 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/browser_main_parts_impl.h"
#include "base/base_switches.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/run_loop.h"
#include "base/task/current_thread.h"
#include "base/task/task_traits.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "cc/base/switches.h"
#include "components/captive_portal/core/buildflags.h"
#include "components/performance_manager/embedder/graph_features.h"
#include "components/performance_manager/embedder/performance_manager_lifetime.h"
#include "components/prefs/pref_service.h"
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#include "components/subresource_filter/content/browser/ruleset_service.h"
#include "components/translate/core/browser/translate_download_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/page_visibility_state.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/url_constants.h"
#include "ui/base/resource/resource_bundle.h"
#include "weblayer/browser/accept_languages_service_factory.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/cookie_settings_factory.h"
#include "weblayer/browser/feature_list_creator.h"
#include "weblayer/browser/heavy_ad_service_factory.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/i18n_util.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_link_manager_factory.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h"
#include "weblayer/browser/origin_trials_factory.h"
#include "weblayer/browser/permissions/weblayer_permissions_client.h"
#include "weblayer/browser/stateful_ssl_host_state_delegate_factory.h"
#include "weblayer/browser/subresource_filter_profile_context_factory.h"
#include "weblayer/browser/translate_ranker_factory.h"
#include "weblayer/browser/web_data_service_factory.h"
#include "weblayer/browser/webui/web_ui_controller_factory.h"
#include "weblayer/grit/weblayer_resources.h"
#include "weblayer/public/main.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/command_line.h"
#include "components/crash/content/browser/child_exit_observer_android.h"
#include "components/crash/content/browser/child_process_crash_observer_android.h"
#include "components/crash/core/common/crash_key.h"
#include "components/javascript_dialogs/android/app_modal_dialog_view_android.h" // nogncheck
#include "components/javascript_dialogs/app_modal_dialog_manager.h" // nogncheck
#include "components/metrics/metrics_service.h"
#include "components/variations/synthetic_trials_active_group_id_provider.h"
#include "components/variations/variations_ids_provider.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_switches.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "weblayer/browser/android/metrics/uma_utils.h"
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#include "weblayer/browser/java/jni/MojoInterfaceRegistrar_jni.h"
#include "weblayer/browser/media/local_presentation_manager_factory.h"
#include "weblayer/browser/media/media_router_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_metrics_collector_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.h"
#include "weblayer/browser/site_engagement/site_engagement_service_factory.h"
#include "weblayer/browser/webapps/weblayer_webapps_client.h"
#include "weblayer/browser/weblayer_factory_impl_android.h"
#include "weblayer/common/features.h"
#endif
// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if defined(USE_AURA) && (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
#include "ui/base/ime/init/input_method_initializer.h"
#endif
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
#include "weblayer/browser/captive_portal_service_factory.h"
#endif
namespace weblayer {
namespace {
// Indexes and publishes the subresource filter ruleset data from resources in
// the resource bundle.
void PublishSubresourceFilterRulesetFromResourceBundle() {
// First obtain the version of the ruleset data from the manifest.
std::string ruleset_manifest_string =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_SUBRESOURCE_FILTER_UNINDEXED_RULESET_MANIFEST_JSON);
auto ruleset_manifest = base::JSONReader::Read(ruleset_manifest_string);
DCHECK(ruleset_manifest);
std::string* content_version = ruleset_manifest->FindStringKey("version");
// Instruct the RulesetService to obtain the unindexed ruleset data from the
// ResourceBundle and give it the version of that data.
auto* ruleset_service =
BrowserProcess::GetInstance()->subresource_filter_ruleset_service();
subresource_filter::UnindexedRulesetInfo ruleset_info;
ruleset_info.resource_id = IDR_SUBRESOURCE_FILTER_UNINDEXED_RULESET;
ruleset_info.content_version = *content_version;
ruleset_service->IndexAndStoreAndPublishRulesetIfNeeded(ruleset_info);
}
// Instantiates all weblayer KeyedService factories, which is
// especially important for services that should be created at profile
// creation time as compared to lazily on first access.
void EnsureBrowserContextKeyedServiceFactoriesBuilt() {
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
CaptivePortalServiceFactory::GetInstance();
#endif
HeavyAdServiceFactory::GetInstance();
HostContentSettingsMapFactory::GetInstance();
StatefulSSLHostStateDelegateFactory::GetInstance();
CookieSettingsFactory::GetInstance();
AcceptLanguagesServiceFactory::GetInstance();
TranslateRankerFactory::GetInstance();
NoStatePrefetchLinkManagerFactory::GetInstance();
NoStatePrefetchManagerFactory::GetInstance();
SubresourceFilterProfileContextFactory::GetInstance();
OriginTrialsFactory::GetInstance();
#if BUILDFLAG(IS_ANDROID)
SiteEngagementServiceFactory::GetInstance();
SafeBrowsingMetricsCollectorFactory::GetInstance();
SafeBrowsingNavigationObserverManagerFactory::GetInstance();
if (MediaRouterFactory::IsFeatureEnabled()) {
LocalPresentationManagerFactory::GetInstance();
MediaRouterFactory::GetInstance();
}
#endif
WebDataServiceFactory::GetInstance();
}
void StopMessageLoop(base::OnceClosure quit_closure) {
for (auto it = content::RenderProcessHost::AllHostsIterator(); !it.IsAtEnd();
it.Advance()) {
it.GetCurrentValue()->DisableRefCounts();
}
std::move(quit_closure).Run();
}
} // namespace
BrowserMainPartsImpl::BrowserMainPartsImpl(
MainParams* params,
std::unique_ptr<PrefService> local_state)
: params_(params), local_state_(std::move(local_state)) {}
BrowserMainPartsImpl::~BrowserMainPartsImpl() = default;
int BrowserMainPartsImpl::PreCreateThreads() {
// Make sure permissions client has been set.
WebLayerPermissionsClient::GetInstance();
#if BUILDFLAG(IS_ANDROID)
// The ChildExitObserver needs to be created before any child process is
// created because it needs to be notified during process creation.
child_exit_observer_ = std::make_unique<crash_reporter::ChildExitObserver>();
child_exit_observer_->RegisterClient(
std::make_unique<crash_reporter::ChildProcessCrashObserver>());
crash_reporter::InitializeCrashKeys();
// WebLayer initializes the MetricsService once consent is determined.
// Determining consent is async and potentially slow. VariationsIdsProvider
// is responsible for updating the X-Client-Data header.
// SyntheticTrialsActiveGroupIdProvider is responsible for updating the
// variations crash keys. To ensure the header and crash keys are always
// provided, they are registered now.
//
// Chrome registers these providers from PreCreateThreads() as well.
auto* synthetic_trial_registry = WebLayerMetricsServiceClient::GetInstance()
->GetMetricsService()
->GetSyntheticTrialRegistry();
synthetic_trial_registry->AddSyntheticTrialObserver(
variations::VariationsIdsProvider::GetInstance());
synthetic_trial_registry->AddSyntheticTrialObserver(
variations::SyntheticTrialsActiveGroupIdProvider::GetInstance());
#endif
return content::RESULT_CODE_NORMAL_EXIT;
}
int BrowserMainPartsImpl::PreEarlyInitialization() {
browser_process_ = std::make_unique<BrowserProcess>(std::move(local_state_));
// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if defined(USE_AURA) && (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
ui::InitializeInputMethodForTesting();
#endif
#if BUILDFLAG(IS_ANDROID)
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
WebLayerWebappsClient::Create();
#endif
return content::RESULT_CODE_NORMAL_EXIT;
}
void BrowserMainPartsImpl::PostCreateThreads() {
performance_manager_lifetime_ =
std::make_unique<performance_manager::PerformanceManagerLifetime>(
performance_manager::GraphFeatures::WithMinimal()
// Reports performance-related UMA/UKM.
.EnableMetricsCollector(),
base::DoNothing());
translate::TranslateDownloadManager* download_manager =
translate::TranslateDownloadManager::GetInstance();
download_manager->set_url_loader_factory(
BrowserProcess::GetInstance()->GetSharedURLLoaderFactory());
download_manager->set_application_locale(i18n::GetApplicationLocale());
}
int BrowserMainPartsImpl::PreMainMessageLoopRun() {
FeatureListCreator::GetInstance()->PerformPreMainMessageLoopStartup();
// It's necessary to have a complete dependency graph of
// BrowserContextKeyedServices before calling out to the delegate (which
// will potentially create a profile), so that a profile creation message is
// properly dispatched to the factories that want to create their services
// at profile creation time.
EnsureBrowserContextKeyedServiceFactoriesBuilt();
params_->delegate->PreMainMessageLoopRun();
content::WebUIControllerFactory::RegisterFactory(
WebUIControllerFactory::GetInstance());
BrowserProcess::GetInstance()->PreMainMessageLoopRun();
// Publish the ruleset data. On the vast majority of runs this will
// effectively be a no-op as the version of the data changes at most once per
// release. Nonetheless, post it as a best-effort task to take it off the
// critical path of startup. Note that best-effort tasks are guaranteed to
// execute within a reasonable delay (assuming of course that the app isn't
// shut down first).
content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
->PostTask(
FROM_HERE,
base::BindOnce(&PublishSubresourceFilterRulesetFromResourceBundle));
#if BUILDFLAG(IS_ANDROID)
// On Android, retrieve the application start time from Java and record it. On
// other platforms, the application start time was already recorded in the
// constructor of ContentMainDelegateImpl.
startup_metric_utils::RecordApplicationStartTime(GetApplicationStartTime());
#endif // BUILDFLAG(IS_ANDROID)
// Record the time at which the main message loop starts. Must be recorded
// after application start time (see startup_metric_utils.h).
startup_metric_utils::RecordBrowserMainMessageLoopStart(
base::TimeTicks::Now(), /* is_first_run */ false);
#if BUILDFLAG(IS_ANDROID)
memory_metrics_logger_ = std::make_unique<metrics::MemoryMetricsLogger>();
// Set the global singleton app modal dialog factory.
javascript_dialogs::AppModalDialogManager::GetInstance()
->SetNativeDialogFactory(base::BindRepeating(
[](javascript_dialogs::AppModalDialogController* controller)
-> javascript_dialogs::AppModalDialogView* {
return new javascript_dialogs::AppModalDialogViewAndroid(
base::android::AttachCurrentThread(), controller,
controller->web_contents()->GetTopLevelNativeWindow());
}));
Java_MojoInterfaceRegistrar_registerMojoInterfaces(
base::android::AttachCurrentThread());
#endif
return content::RESULT_CODE_NORMAL_EXIT;
}
void BrowserMainPartsImpl::WillRunMainMessageLoop(
std::unique_ptr<base::RunLoop>& run_loop) {
// Wrap the method that stops the message loop so we can do other shutdown
// cleanup inside content.
params_->delegate->SetMainMessageLoopQuitClosure(
base::BindOnce(StopMessageLoop, run_loop->QuitClosure()));
}
void BrowserMainPartsImpl::OnFirstIdle() {
startup_metric_utils::RecordBrowserMainLoopFirstIdle(base::TimeTicks::Now());
}
void BrowserMainPartsImpl::PostMainMessageLoopRun() {
params_->delegate->PostMainMessageLoopRun();
browser_process_->StartTearDown();
performance_manager_lifetime_.reset();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_main_parts_impl.cc | C++ | unknown | 13,454 |
// 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_BROWSER_MAIN_PARTS_IMPL_H_
#define WEBLAYER_BROWSER_BROWSER_MAIN_PARTS_IMPL_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "components/embedder_support/android/metrics/memory_metrics_logger.h"
#include "content/public/browser/browser_main_parts.h"
#include "content/public/common/main_function_params.h"
class PrefService;
namespace performance_manager {
class PerformanceManagerLifetime;
}
#if BUILDFLAG(IS_ANDROID)
namespace crash_reporter {
class ChildExitObserver;
}
#endif
namespace weblayer {
class BrowserProcess;
struct MainParams;
class BrowserMainPartsImpl : public content::BrowserMainParts {
public:
BrowserMainPartsImpl(MainParams* params,
std::unique_ptr<PrefService> local_state);
BrowserMainPartsImpl(const BrowserMainPartsImpl&) = delete;
BrowserMainPartsImpl& operator=(const BrowserMainPartsImpl&) = delete;
~BrowserMainPartsImpl() override;
// BrowserMainParts overrides.
int PreCreateThreads() override;
int PreEarlyInitialization() override;
void PostCreateThreads() override;
int PreMainMessageLoopRun() override;
void WillRunMainMessageLoop(
std::unique_ptr<base::RunLoop>& run_loop) override;
void OnFirstIdle() override;
void PostMainMessageLoopRun() override;
private:
raw_ptr<MainParams> params_;
std::unique_ptr<BrowserProcess> browser_process_;
std::unique_ptr<performance_manager::PerformanceManagerLifetime>
performance_manager_lifetime_;
#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<metrics::MemoryMetricsLogger> memory_metrics_logger_;
std::unique_ptr<crash_reporter::ChildExitObserver> child_exit_observer_;
#endif // BUILDFLAG(IS_ANDROID)
// Ownership of this moves to BrowserProcess. See
// ContentBrowserClientImpl::local_state_ for details.
std::unique_ptr<PrefService> local_state_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSER_MAIN_PARTS_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_main_parts_impl.h | C++ | unknown | 2,151 |
// 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/browser_process.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "base/time/default_clock.h"
#include "base/time/default_tick_clock.h"
#include "build/build_config.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/network_time/network_time_tracker.h"
#include "components/prefs/pref_service.h"
#include "components/subresource_filter/content/browser/ruleset_service.h"
#include "content/public/browser/network_quality_observer_factory.h"
#include "content/public/browser/network_service_instance.h"
#include "services/network/public/cpp/network_quality_tracker.h"
#include "weblayer/browser/system_network_context_manager.h"
#include "weblayer/common/weblayer_paths.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#endif
namespace weblayer {
namespace {
BrowserProcess* g_browser_process = nullptr;
} // namespace
BrowserProcess::BrowserProcess(std::unique_ptr<PrefService> local_state)
: local_state_(std::move(local_state)) {
g_browser_process = this;
}
BrowserProcess::~BrowserProcess() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
g_browser_process = nullptr;
SystemNetworkContextManager::DeleteInstance();
}
// static
BrowserProcess* BrowserProcess::GetInstance() {
return g_browser_process;
}
void BrowserProcess::PreMainMessageLoopRun() {
CreateNetworkQualityObserver();
}
void BrowserProcess::StartTearDown() {
if (local_state_)
local_state_->CommitPendingWrite();
}
PrefService* BrowserProcess::GetLocalState() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return local_state_.get();
}
scoped_refptr<network::SharedURLLoaderFactory>
BrowserProcess::GetSharedURLLoaderFactory() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return SystemNetworkContextManager::GetInstance()
->GetSharedURLLoaderFactory();
}
network_time::NetworkTimeTracker* BrowserProcess::GetNetworkTimeTracker() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!network_time_tracker_) {
network_time_tracker_ = std::make_unique<network_time::NetworkTimeTracker>(
base::WrapUnique(new base::DefaultClock()),
base::WrapUnique(new base::DefaultTickClock()), GetLocalState(),
GetSharedURLLoaderFactory());
}
return network_time_tracker_.get();
}
network::NetworkQualityTracker* BrowserProcess::GetNetworkQualityTracker() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!network_quality_tracker_) {
network_quality_tracker_ = std::make_unique<network::NetworkQualityTracker>(
base::BindRepeating(&content::GetNetworkService));
}
return network_quality_tracker_.get();
}
subresource_filter::RulesetService*
BrowserProcess::subresource_filter_ruleset_service() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!subresource_filter_ruleset_service_)
CreateSubresourceFilterRulesetService();
return subresource_filter_ruleset_service_.get();
}
void BrowserProcess::CreateNetworkQualityObserver() {
DCHECK(!network_quality_observer_);
network_quality_observer_ =
content::CreateNetworkQualityObserver(GetNetworkQualityTracker());
DCHECK(network_quality_observer_);
}
void BrowserProcess::CreateSubresourceFilterRulesetService() {
DCHECK(!subresource_filter_ruleset_service_);
base::FilePath user_data_dir;
CHECK(base::PathService::Get(DIR_USER_DATA, &user_data_dir));
subresource_filter_ruleset_service_ =
subresource_filter::RulesetService::Create(GetLocalState(), user_data_dir
#ifdef OHOS_ARKWEB_ADBLOCK
,
nullptr
#endif // OHOS_ARKWEB_ADBLOCK
);
}
#if BUILDFLAG(IS_ANDROID)
SafeBrowsingService* BrowserProcess::GetSafeBrowsingService() {
if (!safe_browsing_service_) {
// Create and initialize safe_browsing_service on first get.
// Note: Initialize() needs to happen on UI thread.
safe_browsing_service_ =
std::make_unique<SafeBrowsingService>(embedder_support::GetUserAgent());
safe_browsing_service_->Initialize();
}
return safe_browsing_service_.get();
}
void BrowserProcess::StopSafeBrowsingService() {
if (safe_browsing_service_) {
safe_browsing_service_->StopDBManager();
}
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_process.cc | C++ | unknown | 4,549 |
// 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_BROWSER_PROCESS_H_
#define WEBLAYER_BROWSER_BROWSER_PROCESS_H_
#include <memory>
#include "base/memory/scoped_refptr.h"
#include "base/sequence_checker.h"
#include "build/build_config.h"
#include "services/network/public/cpp/network_quality_tracker.h"
class PrefService;
namespace network_time {
class NetworkTimeTracker;
}
namespace network {
class SharedURLLoaderFactory;
}
namespace subresource_filter {
class RulesetService;
}
namespace weblayer {
class SafeBrowsingService;
// Class that holds global state in the browser process. Should be used only on
// the UI thread.
class BrowserProcess {
public:
explicit BrowserProcess(std::unique_ptr<PrefService> local_state);
BrowserProcess(const BrowserProcess&) = delete;
BrowserProcess& operator=(const BrowserProcess&) = delete;
~BrowserProcess();
static BrowserProcess* GetInstance();
// Called after the threads have been created but before the message loops
// starts running. Allows the browser process to do any initialization that
// requires all threads running.
void PreMainMessageLoopRun();
// Does cleanup that needs to occur before threads are torn down.
void StartTearDown();
PrefService* GetLocalState();
scoped_refptr<network::SharedURLLoaderFactory> GetSharedURLLoaderFactory();
network_time::NetworkTimeTracker* GetNetworkTimeTracker();
network::NetworkQualityTracker* GetNetworkQualityTracker();
// Returns the service providing versioned storage for rules used by the Safe
// Browsing subresource filter. May be null.
subresource_filter::RulesetService* subresource_filter_ruleset_service();
#if BUILDFLAG(IS_ANDROID)
SafeBrowsingService* GetSafeBrowsingService();
void StopSafeBrowsingService();
#endif
private:
void CreateNetworkQualityObserver();
void CreateSubresourceFilterRulesetService();
std::unique_ptr<PrefService> local_state_;
std::unique_ptr<network_time::NetworkTimeTracker> network_time_tracker_;
std::unique_ptr<network::NetworkQualityTracker> network_quality_tracker_;
// Listens to NetworkQualityTracker and sends network quality updates to the
// renderer.
std::unique_ptr<
network::NetworkQualityTracker::RTTAndThroughputEstimatesObserver>
network_quality_observer_;
std::unique_ptr<subresource_filter::RulesetService>
subresource_filter_ruleset_service_;
#if BUILDFLAG(IS_ANDROID)
std::unique_ptr<SafeBrowsingService> safe_browsing_service_;
#endif
SEQUENCE_CHECKER(sequence_checker_);
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSER_PROCESS_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browser_process.h | C++ | unknown | 2,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.
#include "weblayer/browser/browsing_data_remover_delegate.h"
#include "base/functional/callback.h"
#include "build/build_config.h"
#include "components/browsing_data/content/browsing_data_helper.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/heavy_ad_intervention/heavy_ad_blocklist.h"
#include "components/heavy_ad_intervention/heavy_ad_service.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browsing_data_filter_builder.h"
#include "content/public/browser/origin_trials_controller_delegate.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/favicon/favicon_service_impl.h"
#include "weblayer/browser/favicon/favicon_service_impl_factory.h"
#include "weblayer/browser/heavy_ad_service_factory.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
namespace weblayer {
BrowsingDataRemoverDelegate::BrowsingDataRemoverDelegate(
content::BrowserContext* browser_context)
: browser_context_(browser_context) {}
BrowsingDataRemoverDelegate::~BrowsingDataRemoverDelegate() = default;
BrowsingDataRemoverDelegate::EmbedderOriginTypeMatcher
BrowsingDataRemoverDelegate::GetOriginTypeMatcher() {
return EmbedderOriginTypeMatcher();
}
bool BrowsingDataRemoverDelegate::MayRemoveDownloadHistory() {
return true;
}
std::vector<std::string>
BrowsingDataRemoverDelegate::GetDomainsForDeferredCookieDeletion(
uint64_t remove_mask) {
return {};
}
void BrowsingDataRemoverDelegate::RemoveEmbedderData(
const base::Time& delete_begin,
const base::Time& delete_end,
uint64_t remove_mask,
content::BrowsingDataFilterBuilder* filter_builder,
uint64_t origin_type_mask,
base::OnceCallback<void(uint64_t)> callback) {
callback_ = std::move(callback);
// Note: if history is ever added to WebLayer, also remove isolated origins
// when history is cleared.
if (remove_mask & DATA_TYPE_ISOLATED_ORIGINS) {
browsing_data::RemoveSiteIsolationData(
user_prefs::UserPrefs::Get(browser_context_));
}
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForBrowserContext(browser_context_);
if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_CACHE) {
browsing_data::RemovePrerenderCacheData(
NoStatePrefetchManagerFactory::GetForBrowserContext(browser_context_));
}
if (remove_mask & DATA_TYPE_FAVICONS) {
auto* service =
FaviconServiceImplFactory::GetForBrowserContext(browser_context_);
if (service) {
// The favicon database doesn't track enough information to remove
// favicons in a time range. Delete everything.
service->DeleteAndRecreateDatabase(CreateTaskCompletionClosure());
}
}
if (remove_mask & DATA_TYPE_AD_INTERVENTIONS) {
heavy_ad_intervention::HeavyAdService* heavy_ad_service =
HeavyAdServiceFactory::GetForBrowserContext(browser_context_);
if (heavy_ad_service->heavy_ad_blocklist()) {
heavy_ad_service->heavy_ad_blocklist()->ClearBlockList(delete_begin,
delete_end);
}
}
// We ignore the DATA_TYPE_COOKIES request if UNPROTECTED_WEB is not set,
// so that callers who request COOKIES_AND_SITE_DATA with PROTECTED_WEB
// don't accidentally remove the cookies that are associated with the
// UNPROTECTED_WEB origin. This is necessary because cookies are not separated
// between UNPROTECTED_WEB and PROTECTED_WEB.
if (remove_mask & content::BrowsingDataRemover::DATA_TYPE_COOKIES) {
network::mojom::NetworkContext* safe_browsing_context = nullptr;
#if BUILDFLAG(IS_ANDROID)
safe_browsing_context = BrowserProcess::GetInstance()
->GetSafeBrowsingService()
->GetNetworkContext();
#endif
browsing_data::RemoveEmbedderCookieData(
delete_begin, delete_end, filter_builder, host_content_settings_map,
safe_browsing_context,
base::BindOnce(
&BrowsingDataRemoverDelegate::CreateTaskCompletionClosure,
base::Unretained(this)));
}
if (remove_mask & DATA_TYPE_SITE_SETTINGS) {
browsing_data::RemoveSiteSettingsData(delete_begin, delete_end,
host_content_settings_map);
content::OriginTrialsControllerDelegate* delegate =
browser_context_->GetOriginTrialsControllerDelegate();
if (delegate)
delegate->ClearPersistedTokens();
}
RunCallbackIfDone();
}
base::OnceClosure BrowsingDataRemoverDelegate::CreateTaskCompletionClosure() {
++pending_tasks_;
return base::BindOnce(&BrowsingDataRemoverDelegate::OnTaskComplete,
weak_ptr_factory_.GetWeakPtr());
}
void BrowsingDataRemoverDelegate::OnTaskComplete() {
pending_tasks_--;
RunCallbackIfDone();
}
void BrowsingDataRemoverDelegate::RunCallbackIfDone() {
if (pending_tasks_ != 0)
return;
std::move(callback_).Run(/*failed_data_types=*/0);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browsing_data_remover_delegate.cc | C++ | unknown | 5,459 |
// 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_BROWSING_DATA_REMOVER_DELEGATE_H_
#define WEBLAYER_BROWSER_BROWSING_DATA_REMOVER_DELEGATE_H_
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "components/keyed_service/core/keyed_service.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/browsing_data_remover_delegate.h"
namespace content {
class BrowserContext;
}
namespace weblayer {
class BrowsingDataRemoverDelegate : public content::BrowsingDataRemoverDelegate,
public KeyedService {
public:
// This is an extension of content::BrowsingDataRemover::RemoveDataMask which
// includes all datatypes therefrom and adds additional WebLayer-specific
// ones.
enum DataType : uint64_t {
// Embedder can start adding datatypes after the last platform datatype.
DATA_TYPE_EMBEDDER_BEGIN =
content::BrowsingDataRemover::DATA_TYPE_CONTENT_END << 1,
// WebLayer-specific datatypes.
DATA_TYPE_ISOLATED_ORIGINS = DATA_TYPE_EMBEDDER_BEGIN,
DATA_TYPE_FAVICONS = DATA_TYPE_EMBEDDER_BEGIN << 1,
DATA_TYPE_SITE_SETTINGS = DATA_TYPE_EMBEDDER_BEGIN << 2,
DATA_TYPE_AD_INTERVENTIONS = DATA_TYPE_EMBEDDER_BEGIN << 4,
};
explicit BrowsingDataRemoverDelegate(
content::BrowserContext* browser_context);
~BrowsingDataRemoverDelegate() override;
BrowsingDataRemoverDelegate(const BrowsingDataRemoverDelegate&) = delete;
BrowsingDataRemoverDelegate& operator=(const BrowsingDataRemoverDelegate&) =
delete;
// content::BrowsingDataRemoverDelegate:
EmbedderOriginTypeMatcher GetOriginTypeMatcher() override;
bool MayRemoveDownloadHistory() override;
std::vector<std::string> GetDomainsForDeferredCookieDeletion(
uint64_t remove_mask) override;
void RemoveEmbedderData(const base::Time& delete_begin,
const base::Time& delete_end,
uint64_t remove_mask,
content::BrowsingDataFilterBuilder* filter_builder,
uint64_t origin_type_mask,
base::OnceCallback<void(uint64_t)> callback) override;
private:
base::OnceClosure CreateTaskCompletionClosure();
void OnTaskComplete();
void RunCallbackIfDone();
raw_ptr<content::BrowserContext> browser_context_ = nullptr;
int pending_tasks_ = 0;
// Completion callback to call when all data are deleted.
base::OnceCallback<void(uint64_t)> callback_;
base::WeakPtrFactory<BrowsingDataRemoverDelegate> weak_ptr_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSING_DATA_REMOVER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browsing_data_remover_delegate.h | C++ | unknown | 2,833 |
// 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/browsing_data_remover_delegate_factory.h"
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "weblayer/browser/browsing_data_remover_delegate.h"
namespace weblayer {
// static
BrowsingDataRemoverDelegate*
BrowsingDataRemoverDelegateFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<BrowsingDataRemoverDelegate*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
BrowsingDataRemoverDelegateFactory*
BrowsingDataRemoverDelegateFactory::GetInstance() {
static base::NoDestructor<BrowsingDataRemoverDelegateFactory> factory;
return factory.get();
}
BrowsingDataRemoverDelegateFactory::BrowsingDataRemoverDelegateFactory()
: BrowserContextKeyedServiceFactory(
"BrowsingDataRemoverDelegate",
BrowserContextDependencyManager::GetInstance()) {}
BrowsingDataRemoverDelegateFactory::~BrowsingDataRemoverDelegateFactory() =
default;
KeyedService* BrowsingDataRemoverDelegateFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new BrowsingDataRemoverDelegate(context);
}
content::BrowserContext*
BrowsingDataRemoverDelegateFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browsing_data_remover_delegate_factory.cc | C++ | unknown | 1,542 |
// 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_BROWSING_DATA_REMOVER_DELEGATE_FACTORY_H_
#define WEBLAYER_BROWSER_BROWSING_DATA_REMOVER_DELEGATE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace weblayer {
class BrowsingDataRemoverDelegate;
class BrowsingDataRemoverDelegateFactory
: public BrowserContextKeyedServiceFactory {
public:
BrowsingDataRemoverDelegateFactory(
const BrowsingDataRemoverDelegateFactory&) = delete;
BrowsingDataRemoverDelegateFactory& operator=(
const BrowsingDataRemoverDelegateFactory&) = delete;
static BrowsingDataRemoverDelegate* GetForBrowserContext(
content::BrowserContext* browser_context);
static BrowsingDataRemoverDelegateFactory* GetInstance();
private:
friend class base::NoDestructor<BrowsingDataRemoverDelegateFactory>;
BrowsingDataRemoverDelegateFactory();
~BrowsingDataRemoverDelegateFactory() override;
// BrowserContextKeyedServiceFactory methods:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSING_DATA_REMOVER_DELEGATE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/browsing_data_remover_delegate_factory.h | C++ | unknown | 1,453 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/captive_portal_service_factory.h"
#include "components/captive_portal/content/captive_portal_service.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
namespace weblayer {
// static
captive_portal::CaptivePortalService*
CaptivePortalServiceFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<captive_portal::CaptivePortalService*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
CaptivePortalServiceFactory* CaptivePortalServiceFactory::GetInstance() {
return base::Singleton<CaptivePortalServiceFactory>::get();
}
CaptivePortalServiceFactory::CaptivePortalServiceFactory()
: BrowserContextKeyedServiceFactory(
"captive_portal::CaptivePortalService",
BrowserContextDependencyManager::GetInstance()) {}
CaptivePortalServiceFactory::~CaptivePortalServiceFactory() = default;
KeyedService* CaptivePortalServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* browser_context) const {
return new captive_portal::CaptivePortalService(
browser_context, user_prefs::UserPrefs::Get(browser_context));
}
content::BrowserContext* CaptivePortalServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/captive_portal_service_factory.cc | C++ | unknown | 1,612 |
// 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_CAPTIVE_PORTAL_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_CAPTIVE_PORTAL_SERVICE_FACTORY_H_
#include "base/compiler_specific.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace captive_portal {
class CaptivePortalService;
}
namespace weblayer {
// Singleton that owns all captive_portal::CaptivePortalServices and associates
// them with BrowserContextImpl instances.
class CaptivePortalServiceFactory : public BrowserContextKeyedServiceFactory {
public:
// Returns the captive_portal::CaptivePortalService for |browser_context|.
static captive_portal::CaptivePortalService* GetForBrowserContext(
content::BrowserContext* browser_context);
static CaptivePortalServiceFactory* GetInstance();
private:
friend struct base::DefaultSingletonTraits<CaptivePortalServiceFactory>;
CaptivePortalServiceFactory();
~CaptivePortalServiceFactory() override;
CaptivePortalServiceFactory(const CaptivePortalServiceFactory&) = delete;
CaptivePortalServiceFactory& operator=(const CaptivePortalServiceFactory&) =
delete;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
// Incognito profiles have their own instance of
// captive_portal::CaptivePortalService rather than the default behavior of
// the service being null if the profile is incognito.
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_CAPTIVE_PORTAL_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/captive_portal_service_factory.h | C++ | unknown | 1,816 |
// 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/strings/string_number_conversions.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
class ClientHintsBrowserTest : public WebLayerBrowserTest {
public:
void SetUpOnMainThread() override {
WebLayerBrowserTest::SetUpOnMainThread();
BrowserProcess::GetInstance()
->GetNetworkQualityTracker()
->ReportRTTsAndThroughputForTesting(base::Milliseconds(500), 100);
EXPECT_TRUE(embedded_test_server()->Start());
}
void SetAcceptClientHints() {
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL(
"/set-header?Accept-CH: device-memory,rtt"),
shell());
}
void CheckNavigationHeaders() {
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/echoheader?device-memory"), shell());
double device_memory = 0.0;
ASSERT_TRUE(base::StringToDouble(GetBody(), &device_memory));
EXPECT_GT(device_memory, 0.0);
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/echoheader?rtt"), shell());
int rtt = 0;
ASSERT_TRUE(base::StringToInt(GetBody(), &rtt));
EXPECT_GT(rtt, 0);
}
void CheckSubresourceHeaders() {
double device_memory = 0.0;
ASSERT_TRUE(base::StringToDouble(GetSubresourceHeader("device-memory"),
&device_memory));
EXPECT_GT(device_memory, 0.0);
int rtt = 0;
ASSERT_TRUE(base::StringToInt(GetSubresourceHeader("rtt"), &rtt));
EXPECT_GT(rtt, 0);
}
void KillRenderer() {
content::RenderProcessHost* child_process =
static_cast<TabImpl*>(shell()->tab())
->web_contents()
->GetPrimaryMainFrame()
->GetProcess();
content::RenderProcessHostWatcher crash_observer(
child_process,
content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
child_process->Shutdown(0);
crash_observer.Wait();
}
std::string GetSubresourceHeader(const std::string& header) {
constexpr char kScript[] = R"(
new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open("GET", "/echoheader?" + $1);
xhr.onload = () => {
resolve(xhr.response);
};
xhr.send();
})
)";
content::WebContents* web_contents =
static_cast<TabImpl*>(shell()->tab())->web_contents();
return content::EvalJs(web_contents,
content::JsReplace(kScript, "device-memory"))
.ExtractString();
}
std::string GetBody() {
return ExecuteScript(shell(), "document.body.innerText", true).GetString();
}
};
IN_PROC_BROWSER_TEST_F(ClientHintsBrowserTest, Navigation) {
SetAcceptClientHints();
CheckNavigationHeaders();
}
IN_PROC_BROWSER_TEST_F(ClientHintsBrowserTest, Subresource) {
SetAcceptClientHints();
CheckSubresourceHeaders();
}
IN_PROC_BROWSER_TEST_F(ClientHintsBrowserTest, SubresourceInNewRenderer) {
SetAcceptClientHints();
KillRenderer();
NavigateAndWaitForCompletion(embedded_test_server()->GetURL("/echo"),
shell());
CheckSubresourceHeaders();
}
IN_PROC_BROWSER_TEST_F(ClientHintsBrowserTest,
SubresourceAfterContentSettingUpdate) {
// Set accept client hints on the original server.
SetAcceptClientHints();
// Start a new server which will not accept client hints.
net::test_server::EmbeddedTestServer other_server;
net::test_server::RegisterDefaultHandlers(&other_server);
ASSERT_TRUE(other_server.Start());
NavigateAndWaitForCompletion(other_server.GetURL("/echo"), shell());
EXPECT_EQ(GetSubresourceHeader("device-memory"), "None");
// Copy client hints over to the other server.
auto* settings_map = HostContentSettingsMapFactory::GetForBrowserContext(
static_cast<TabImpl*>(shell()->tab())
->web_contents()
->GetBrowserContext());
base::Value setting = settings_map->GetWebsiteSetting(
embedded_test_server()->base_url(), GURL(),
ContentSettingsType::CLIENT_HINTS, nullptr);
ASSERT_FALSE(setting.is_none());
settings_map->SetWebsiteSettingDefaultScope(other_server.base_url(), GURL(),
ContentSettingsType::CLIENT_HINTS,
setting.Clone());
// Settings take affect after navigation only, so the header shouldn't be
// there yet.
EXPECT_EQ(GetSubresourceHeader("device-memory"), "None");
// After re-navigating, should have hints.
NavigateAndWaitForCompletion(other_server.GetURL("/echo"), shell());
CheckSubresourceHeaders();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/client_hints_browsertest.cc | C++ | unknown | 5,335 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/client_hints_factory.h"
#include "base/no_destructor.h"
#include "components/client_hints/browser/client_hints.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/cookie_settings_factory.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
client_hints::ClientHints* ClientHintsFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<client_hints::ClientHints*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
// static
ClientHintsFactory* ClientHintsFactory::GetInstance() {
static base::NoDestructor<ClientHintsFactory> factory;
return factory.get();
}
ClientHintsFactory::ClientHintsFactory()
: BrowserContextKeyedServiceFactory(
"ClientHints",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
DependsOn(CookieSettingsFactory::GetInstance());
}
ClientHintsFactory::~ClientHintsFactory() = default;
KeyedService* ClientHintsFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new client_hints::ClientHints(
context, BrowserProcess::GetInstance()->GetNetworkQualityTracker(),
HostContentSettingsMapFactory::GetForBrowserContext(context),
CookieSettingsFactory::GetForBrowserContext(context),
BrowserProcess::GetInstance()->GetLocalState());
}
content::BrowserContext* ClientHintsFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/client_hints_factory.cc | C++ | unknown | 1,916 |
// 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_CLIENT_HINTS_FACTORY_H_
#define WEBLAYER_BROWSER_CLIENT_HINTS_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace client_hints {
class ClientHints;
}
namespace weblayer {
class ClientHintsFactory : public BrowserContextKeyedServiceFactory {
public:
ClientHintsFactory(const ClientHintsFactory&) = delete;
ClientHintsFactory& operator=(const ClientHintsFactory&) = delete;
static client_hints::ClientHints* GetForBrowserContext(
content::BrowserContext* browser_context);
static ClientHintsFactory* GetInstance();
private:
friend class base::NoDestructor<ClientHintsFactory>;
ClientHintsFactory();
~ClientHintsFactory() override;
// BrowserContextKeyedServiceFactory methods:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* profile) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_CLIENT_HINTS_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/client_hints_factory.h | C++ | unknown | 1,247 |
// 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 <string>
#include "components/permissions/permission_request_manager.h"
#include "components/permissions/test/mock_permission_prompt_factory.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/scoped_page_focus_override.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
class ClipboardBrowserTest : public WebLayerBrowserTest {
public:
ClipboardBrowserTest() = default;
~ClipboardBrowserTest() override = default;
// WebLayerBrowserTest:
void SetUpOnMainThread() override {
WebLayerBrowserTest::SetUpOnMainThread();
permissions::PermissionRequestManager* manager =
permissions::PermissionRequestManager::FromWebContents(
GetWebContents());
prompt_factory_ =
std::make_unique<permissions::MockPermissionPromptFactory>(manager);
title_watcher_ =
std::make_unique<content::TitleWatcher>(GetWebContents(), u"success");
title_watcher_->AlsoWaitForTitle(u"fail");
EXPECT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/clipboard.html"), shell());
// The Clipboard API requires the page to have focus.
scoped_focus_ =
std::make_unique<content::ScopedPageFocusOverride>(GetWebContents());
}
void TearDownOnMainThread() override {
scoped_focus_.reset();
title_watcher_.reset();
prompt_factory_.reset();
}
protected:
content::WebContents* GetWebContents() {
return static_cast<TabImpl*>(shell()->tab())->web_contents();
}
GURL GetBaseOrigin() {
return embedded_test_server()->base_url().DeprecatedGetOriginAsURL();
}
permissions::MockPermissionPromptFactory* prompt_factory() {
return prompt_factory_.get();
}
content::TitleWatcher* title_watcher() { return title_watcher_.get(); }
private:
std::unique_ptr<permissions::MockPermissionPromptFactory> prompt_factory_;
std::unique_ptr<content::TitleWatcher> title_watcher_;
std::unique_ptr<content::ScopedPageFocusOverride> scoped_focus_;
};
IN_PROC_BROWSER_TEST_F(ClipboardBrowserTest, ReadTextSuccess) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
ExecuteScriptWithUserGesture(shell()->tab(), "tryClipboardReadText()");
EXPECT_EQ(u"success", title_watcher()->WaitAndGetTitle());
EXPECT_EQ(1, prompt_factory()->TotalRequestCount());
EXPECT_TRUE(prompt_factory()->RequestOriginSeen(GetBaseOrigin()));
}
IN_PROC_BROWSER_TEST_F(ClipboardBrowserTest, WriteSanitizedTextSuccess) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::ACCEPT_ALL);
ExecuteScriptWithUserGesture(shell()->tab(), "tryClipboardWriteText()");
EXPECT_EQ(u"success", title_watcher()->WaitAndGetTitle());
// Writing sanitized data to the clipboard does not require a permission.
EXPECT_EQ(0, prompt_factory()->TotalRequestCount());
}
IN_PROC_BROWSER_TEST_F(ClipboardBrowserTest, ReadTextWithoutPermission) {
prompt_factory()->set_response_type(
permissions::PermissionRequestManager::DENY_ALL);
ExecuteScriptWithUserGesture(shell()->tab(), "tryClipboardReadText()");
EXPECT_EQ(u"fail", title_watcher()->WaitAndGetTitle());
EXPECT_EQ(1, prompt_factory()->TotalRequestCount());
EXPECT_TRUE(prompt_factory()->RequestOriginSeen(GetBaseOrigin()));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/clipboard_browsertest.cc | C++ | unknown | 3,730 |
include_rules = [
"+components/component_updater/installer_policies",
] | Zhao-PengFei35/chromium_src_4 | weblayer/browser/component_updater/DEPS | Python | unknown | 73 |
// 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/component_updater/client_side_phishing_component_loader_policy.h"
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
#include "base/check.h"
#include "base/containers/flat_map.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/location.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/values.h"
#include "base/version.h"
#include "components/component_updater/android/component_loader_policy.h"
#include "components/component_updater/installer_policies/client_side_phishing_component_installer_policy.h"
#include "components/safe_browsing/content/browser/client_side_phishing_model.h"
#include "weblayer/common/features.h"
namespace weblayer {
namespace {
// Persisted to logs, should never change.
constexpr char kClientSidePhishingComponentMetricsSuffix[] =
"ClientSidePhishing";
void LoadFromDisk(base::ScopedFD pb_fd, base::ScopedFD visual_tflite_model_fd) {
std::string binary_pb;
base::ScopedFILE pb_file_stream(
base::FileToFILE(base::File(std::move(pb_fd)), "r"));
if (!base::ReadStreamToString(pb_file_stream.get(), &binary_pb))
binary_pb.clear();
base::File visual_tflite_model(std::move(visual_tflite_model_fd),
base::File::FLAG_OPEN | base::File::FLAG_READ);
// The ClientSidePhishingModel singleton will react appropriately if the
// |binary_pb| is empty or |visual_tflite_model| is invalid.
safe_browsing::ClientSidePhishingModel::GetInstance()
->PopulateFromDynamicUpdate(binary_pb, std::move(visual_tflite_model));
}
} // namespace
void ClientSidePhishingComponentLoaderPolicy::ComponentLoaded(
const base::Version& version,
base::flat_map<std::string, base::ScopedFD>& fd_map,
base::Value::Dict manifest) {
DCHECK(version.IsValid());
auto pb_iterator =
fd_map.find(component_updater::kClientModelBinaryPbFileName);
if (pb_iterator == fd_map.end())
return;
auto visual_tflite_model_iterator =
fd_map.find(component_updater::kVisualTfLiteModelFileName);
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&LoadFromDisk, std::move(pb_iterator->second),
visual_tflite_model_iterator == fd_map.end()
? base::ScopedFD()
: std::move(visual_tflite_model_iterator->second)));
}
void ClientSidePhishingComponentLoaderPolicy::ComponentLoadFailed(
component_updater::ComponentLoadResult /*error*/) {}
void ClientSidePhishingComponentLoaderPolicy::GetHash(
std::vector<uint8_t>* hash) const {
component_updater::ClientSidePhishingComponentInstallerPolicy::GetPublicHash(
hash);
}
std::string ClientSidePhishingComponentLoaderPolicy::GetMetricsSuffix() const {
return kClientSidePhishingComponentMetricsSuffix;
}
void LoadClientSidePhishingComponent(
component_updater::ComponentLoaderPolicyVector& policies) {
if (!base::FeatureList::IsEnabled(
weblayer::features::kWebLayerClientSidePhishingDetection)) {
return;
}
policies.push_back(
std::make_unique<ClientSidePhishingComponentLoaderPolicy>());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/component_updater/client_side_phishing_component_loader_policy.cc | C++ | unknown | 3,441 |
// 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_COMPONENT_UPDATER_CLIENT_SIDE_PHISHING_COMPONENT_LOADER_POLICY_H_
#define WEBLAYER_BROWSER_COMPONENT_UPDATER_CLIENT_SIDE_PHISHING_COMPONENT_LOADER_POLICY_H_
#include <stdint.h>
#include <string>
#include <vector>
#include "base/containers/flat_map.h"
#include "base/files/scoped_file.h"
#include "base/values.h"
#include "components/component_updater/android/component_loader_policy.h"
namespace base {
class Version;
} // namespace base
namespace weblayer {
class ClientSidePhishingComponentLoaderPolicy
: public component_updater::ComponentLoaderPolicy {
public:
ClientSidePhishingComponentLoaderPolicy() = default;
~ClientSidePhishingComponentLoaderPolicy() override = default;
ClientSidePhishingComponentLoaderPolicy(
const ClientSidePhishingComponentLoaderPolicy&) = delete;
ClientSidePhishingComponentLoaderPolicy& operator=(
const ClientSidePhishingComponentLoaderPolicy&) = delete;
private:
// The following methods override ComponentLoaderPolicy.
void ComponentLoaded(const base::Version& version,
base::flat_map<std::string, base::ScopedFD>& fd_map,
base::Value::Dict manifest) override;
void ComponentLoadFailed(
component_updater::ComponentLoadResult error) override;
void GetHash(std::vector<uint8_t>* hash) const override;
std::string GetMetricsSuffix() const override;
};
void LoadClientSidePhishingComponent(
component_updater::ComponentLoaderPolicyVector& policies);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_COMPONENT_UPDATER_CLIENT_SIDE_PHISHING_COMPONENT_LOADER_POLICY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/component_updater/client_side_phishing_component_loader_policy.h | C++ | unknown | 1,776 |
// 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/component_updater/registration.h"
#include "weblayer/browser/component_updater/client_side_phishing_component_loader_policy.h"
namespace weblayer {
component_updater::ComponentLoaderPolicyVector GetComponentLoaderPolicies() {
component_updater::ComponentLoaderPolicyVector policies;
LoadClientSidePhishingComponent(policies);
// TODO(crbug.com/1233490) register AutoFillRegex component loader policy.
return policies;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/component_updater/registration.cc | C++ | unknown | 630 |
// 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_COMPONENT_UPDATER_REGISTRATION_H_
#define WEBLAYER_BROWSER_COMPONENT_UPDATER_REGISTRATION_H_
#include "components/component_updater/android/component_loader_policy.h"
namespace weblayer {
// ComponentLoaderPolicies for component to load in WebLayer during startup.
component_updater::ComponentLoaderPolicyVector GetComponentLoaderPolicies();
} // namespace weblayer
#endif // WEBLAYER_BROWSER_COMPONENT_UPDATER_REGISTRATION_H_ | Zhao-PengFei35/chromium_src_4 | weblayer/browser/component_updater/registration.h | C++ | unknown | 602 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/content_browser_client_impl.h"
#include <memory>
#include <utility>
#include "base/command_line.h"
#include "base/containers/flat_set.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/strings/string_piece.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/autofill/content/browser/content_autofill_driver_factory.h"
#include "components/blocked_content/popup_blocker.h"
#include "components/captive_portal/core/buildflags.h"
#include "components/content_capture/browser/onscreen_content_provider.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/embedder_support/content_settings_utils.h"
#include "components/embedder_support/switches.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/error_page/common/error.h"
#include "components/error_page/common/localized_error.h"
#include "components/error_page/content/browser/net_error_auto_reloader.h"
#include "components/metrics/metrics_service.h"
#include "components/network_time/network_time_tracker.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
#include "components/no_state_prefetch/common/prerender_url_loader_throttle.h"
#include "components/page_load_metrics/browser/metrics_navigation_throttle.h"
#include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
#include "components/performance_manager/embedder/performance_manager_registry.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service_factory.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_interstitials/content/insecure_form_navigation_throttle.h"
#include "components/security_interstitials/content/security_interstitial_tab_helper.h"
#include "components/security_interstitials/content/ssl_cert_reporter.h"
#include "components/security_interstitials/content/ssl_error_handler.h"
#include "components/security_interstitials/content/ssl_error_navigation_throttle.h"
#include "components/site_isolation/pref_names.h"
#include "components/site_isolation/preloaded_isolated_origins.h"
#include "components/site_isolation/site_isolation_policy.h"
#include "components/strings/grit/components_locale_settings.h"
#include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h"
#include "components/subresource_filter/content/browser/ruleset_version.h"
#include "components/user_prefs/user_prefs.h"
#include "components/variations/service/variations_service.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/devtools_manager_delegate.h"
#include "content/public/browser/generated_code_cache_settings.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/navigation_throttle.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/permission_controller.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/window_container_type.mojom.h"
#include "mojo/public/cpp/bindings/binder_map.h"
#include "net/cert/x509_certificate.h"
#include "net/cookies/site_for_cookies.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/ssl/client_cert_identity.h"
#include "net/ssl/ssl_private_key.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/network_service.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/loader/url_loader_throttle.h"
#include "third_party/blink/public/common/permissions/permission_utils.h"
#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/url_constants.h"
#include "weblayer/browser/browser_main_parts_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/cookie_settings_factory.h"
#include "weblayer/browser/download_manager_delegate_impl.h"
#include "weblayer/browser/feature_list_creator.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_error_navigation_throttle.h"
#include "weblayer/browser/navigation_ui_data_impl.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h"
#include "weblayer/browser/no_state_prefetch/no_state_prefetch_utils.h"
#include "weblayer/browser/page_specific_content_settings_delegate.h"
#include "weblayer/browser/password_manager_driver_factory.h"
#include "weblayer/browser/popup_navigation_delegate_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/signin_url_loader_throttle.h"
#include "weblayer/browser/system_network_context_manager.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/browser/web_contents_view_delegate_impl.h"
#include "weblayer/browser/weblayer_browser_interface_binders.h"
#include "weblayer/browser/weblayer_security_blocking_page_factory.h"
#include "weblayer/browser/weblayer_speech_recognition_manager_delegate.h"
#include "weblayer/common/features.h"
#include "weblayer/common/weblayer_paths.h"
#include "weblayer/public/fullscreen_delegate.h"
#include "weblayer/public/main.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/bundle_utils.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/path_utils.h"
#include "base/functional/bind.h"
#include "components/browser_ui/client_certificate/android/ssl_client_certificate_request.h"
#include "components/cdm/browser/cdm_message_filter_android.h"
#include "components/cdm/browser/media_drm_storage_impl.h" // nogncheck
#include "components/crash/content/browser/crash_handler_host_linux.h"
#include "components/embedder_support/android/metrics/android_metrics_service_client.h"
#include "components/media_router/browser/presentation/presentation_service_delegate_impl.h" // nogncheck
#include "components/navigation_interception/intercept_navigation_delegate.h"
#include "components/permissions/bluetooth_delegate_impl.h"
#include "components/safe_browsing/core/browser/realtime/policy_engine.h" // nogncheck
#include "components/safe_browsing/core/browser/realtime/url_lookup_service.h" // nogncheck
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/spellcheck/browser/spell_check_host_impl.h" // nogncheck
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "ui/base/resource/resource_bundle_android.h"
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#include "weblayer/browser/android_descriptors.h"
#include "weblayer/browser/bluetooth/weblayer_bluetooth_delegate_impl_client.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/devtools_manager_delegate_android.h"
#include "weblayer/browser/http_auth_handler_impl.h"
#include "weblayer/browser/media/media_router_factory.h"
#include "weblayer/browser/proxying_url_loader_factory_impl.h"
#include "weblayer/browser/safe_browsing/real_time_url_lookup_service_factory.h"
#include "weblayer/browser/safe_browsing/safe_browsing_service.h"
#include "weblayer/browser/tts_environment_android_impl.h"
#include "weblayer/browser/weblayer_factory_impl_android.h"
#endif
// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) || \
BUILDFLAG(IS_ANDROID)
#include "content/public/common/content_descriptors.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "sandbox/policy/win/sandbox_win.h"
#include "sandbox/win/src/sandbox.h"
#endif
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
#include "weblayer/browser/captive_portal_service_factory.h"
#endif
#if BUILDFLAG(ENABLE_ARCORE)
#include "weblayer/browser/xr/xr_integration_client_impl.h"
#endif // BUILDFLAG(ENABLE_ARCORE)
namespace switches {
// Specifies a list of hosts for whom we bypass proxy settings and use direct
// connections. Ignored if --proxy-auto-detect or --no-proxy-server are also
// specified. This is a comma-separated list of bypass rules. See:
// "net/proxy_resolution/proxy_bypass_rules.h" for the format of these rules.
// TODO(alexclarke): Find a better place for this.
const char kProxyBypassList[] = "proxy-bypass-list";
} // namespace switches
namespace weblayer {
namespace {
bool IsSafebrowsingSupported() {
// TODO(timvolodine): consider the non-android case, see crbug.com/1015809.
// TODO(timvolodine): consider refactoring this out into safe_browsing/.
#if BUILDFLAG(IS_ANDROID)
return true;
#else
return false;
#endif
}
bool IsNetworkErrorAutoReloadEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(embedder_support::kEnableAutoReload))
return true;
if (command_line.HasSwitch(embedder_support::kDisableAutoReload))
return false;
return true;
}
bool IsInHostedApp(content::WebContents* web_contents) {
return false;
}
bool ShouldIgnoreInterstitialBecauseNavigationDefaultedToHttps(
content::NavigationHandle* handle) {
return false;
}
class SSLCertReporterImpl : public SSLCertReporter {
public:
void ReportInvalidCertificateChain(
const std::string& serialized_report) override {}
};
// Wrapper for SSLErrorHandler::HandleSSLError() that supplies //weblayer-level
// parameters.
void HandleSSLErrorWrapper(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
SSLErrorHandler::BlockingPageReadyCallback blocking_page_ready_callback) {
captive_portal::CaptivePortalService* captive_portal_service = nullptr;
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
captive_portal_service = CaptivePortalServiceFactory::GetForBrowserContext(
web_contents->GetBrowserContext());
#endif
SSLErrorHandler::HandleSSLError(
web_contents, cert_error, ssl_info, request_url,
std::move(ssl_cert_reporter), std::move(blocking_page_ready_callback),
BrowserProcess::GetInstance()->GetNetworkTimeTracker(),
captive_portal_service,
std::make_unique<WebLayerSecurityBlockingPageFactory>());
}
#if BUILDFLAG(IS_ANDROID)
void CreateOriginId(cdm::MediaDrmStorageImpl::OriginIdObtainedCB callback) {
std::move(callback).Run(true, base::UnguessableToken::Create());
}
void AllowEmptyOriginIdCB(base::OnceCallback<void(bool)> callback) {
// Since CreateOriginId() always returns a non-empty origin ID, we don't need
// to allow empty origin ID.
std::move(callback).Run(false);
}
void CreateMediaDrmStorage(
content::RenderFrameHost* render_frame_host,
mojo::PendingReceiver<::media::mojom::MediaDrmStorage> receiver) {
CHECK(render_frame_host);
if (render_frame_host->GetLastCommittedOrigin().opaque()) {
DVLOG(1) << __func__ << ": Unique origin.";
return;
}
// The object will be deleted on connection error, or when the frame navigates
// away.
new cdm::MediaDrmStorageImpl(
*render_frame_host, base::BindRepeating(&CreateOriginId),
base::BindRepeating(&AllowEmptyOriginIdCB), std::move(receiver));
}
#endif // BUILDFLAG(IS_ANDROID)
void RegisterPrefs(PrefRegistrySimple* pref_registry) {
network_time::NetworkTimeTracker::RegisterPrefs(pref_registry);
pref_registry->RegisterIntegerPref(kDownloadNextIDPref, 0);
#if BUILDFLAG(IS_ANDROID)
metrics::AndroidMetricsServiceClient::RegisterPrefs(pref_registry);
safe_browsing::RegisterLocalStatePrefs(pref_registry);
#else
// Call MetricsService::RegisterPrefs() as VariationsService::RegisterPrefs()
// CHECKs that kVariationsCrashStreak has already been registered.
//
// Note that the above call to AndroidMetricsServiceClient::RegisterPrefs()
// implicitly calls MetricsService::RegisterPrefs(), so the below call is
// necessary only on non-Android platforms.
metrics::MetricsService::RegisterPrefs(pref_registry);
#endif
variations::VariationsService::RegisterPrefs(pref_registry);
subresource_filter::IndexedRulesetVersion::RegisterPrefs(pref_registry);
}
mojo::PendingRemote<prerender::mojom::PrerenderCanceler> GetPrerenderCanceler(
content::WebContents* web_contents) {
mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler;
weblayer::NoStatePrefetchContentsFromWebContents(web_contents)
->AddPrerenderCancelerReceiver(canceler.InitWithNewPipeAndPassReceiver());
return canceler;
}
} // namespace
ContentBrowserClientImpl::ContentBrowserClientImpl(MainParams* params)
: params_(params) {
}
ContentBrowserClientImpl::~ContentBrowserClientImpl() = default;
std::unique_ptr<content::BrowserMainParts>
ContentBrowserClientImpl::CreateBrowserMainParts(
bool /* is_integration_test */) {
// This should be called after CreateFeatureListAndFieldTrials(), which
// creates |local_state_|.
DCHECK(local_state_);
std::unique_ptr<BrowserMainPartsImpl> browser_main_parts =
std::make_unique<BrowserMainPartsImpl>(params_, std::move(local_state_));
return browser_main_parts;
}
std::string ContentBrowserClientImpl::GetApplicationLocale() {
return i18n::GetApplicationLocale();
}
std::string ContentBrowserClientImpl::GetAcceptLangs(
content::BrowserContext* context) {
return i18n::GetAcceptLangs();
}
content::AllowServiceWorkerResult ContentBrowserClientImpl::AllowServiceWorker(
const GURL& scope,
const net::SiteForCookies& site_for_cookies,
const absl::optional<url::Origin>& top_frame_origin,
const GURL& script_url,
content::BrowserContext* context) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
return embedder_support::AllowServiceWorker(
scope, site_for_cookies, top_frame_origin,
CookieSettingsFactory::GetForBrowserContext(context).get(),
HostContentSettingsMapFactory::GetForBrowserContext(context));
}
bool ContentBrowserClientImpl::AllowSharedWorker(
const GURL& worker_url,
const net::SiteForCookies& site_for_cookies,
const absl::optional<url::Origin>& top_frame_origin,
const std::string& name,
const blink::StorageKey& storage_key,
content::BrowserContext* context,
int render_process_id,
int render_frame_id) {
return embedder_support::AllowSharedWorker(
worker_url, site_for_cookies, top_frame_origin, name, storage_key,
render_process_id, render_frame_id,
CookieSettingsFactory::GetForBrowserContext(context).get());
}
void ContentBrowserClientImpl::AllowWorkerFileSystem(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalRenderFrameHostId>& render_frames,
base::OnceCallback<void(bool)> callback) {
std::move(callback).Run(embedder_support::AllowWorkerFileSystem(
url, render_frames,
CookieSettingsFactory::GetForBrowserContext(browser_context).get()));
}
bool ContentBrowserClientImpl::AllowWorkerIndexedDB(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalRenderFrameHostId>& render_frames) {
return embedder_support::AllowWorkerIndexedDB(
url, render_frames,
CookieSettingsFactory::GetForBrowserContext(browser_context).get());
}
bool ContentBrowserClientImpl::AllowWorkerCacheStorage(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalRenderFrameHostId>& render_frames) {
return embedder_support::AllowWorkerCacheStorage(
url, render_frames,
CookieSettingsFactory::GetForBrowserContext(browser_context).get());
}
bool ContentBrowserClientImpl::AllowWorkerWebLocks(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalRenderFrameHostId>& render_frames) {
return embedder_support::AllowWorkerWebLocks(
url, CookieSettingsFactory::GetForBrowserContext(browser_context).get());
}
std::unique_ptr<content::WebContentsViewDelegate>
ContentBrowserClientImpl::GetWebContentsViewDelegate(
content::WebContents* web_contents) {
performance_manager::PerformanceManagerRegistry::GetInstance()
->MaybeCreatePageNodeForWebContents(web_contents);
return std::make_unique<WebContentsViewDelegateImpl>(web_contents);
}
bool ContentBrowserClientImpl::CanShutdownGpuProcessNowOnIOThread() {
return true;
}
std::unique_ptr<content::DevToolsManagerDelegate>
ContentBrowserClientImpl::CreateDevToolsManagerDelegate() {
#if BUILDFLAG(IS_ANDROID)
return std::make_unique<DevToolsManagerDelegateAndroid>();
#else
return std::make_unique<content::DevToolsManagerDelegate>();
#endif
}
void ContentBrowserClientImpl::LogWebFeatureForCurrentPage(
content::RenderFrameHost* render_frame_host,
blink::mojom::WebFeature feature) {
page_load_metrics::MetricsWebContentsObserver::RecordFeatureUsage(
render_frame_host, feature);
}
std::string ContentBrowserClientImpl::GetProduct() {
return version_info::GetProductNameAndVersionForUserAgent();
}
std::string ContentBrowserClientImpl::GetUserAgent() {
return embedder_support::GetUserAgent();
}
std::string ContentBrowserClientImpl::GetFullUserAgent() {
return embedder_support::GetFullUserAgent();
}
std::string ContentBrowserClientImpl::GetReducedUserAgent() {
return embedder_support::GetReducedUserAgent();
}
blink::UserAgentMetadata ContentBrowserClientImpl::GetUserAgentMetadata() {
return embedder_support::GetUserAgentMetadata();
}
void ContentBrowserClientImpl::OverrideWebkitPrefs(
content::WebContents* web_contents,
blink::web_pref::WebPreferences* prefs) {
prefs->default_encoding = l10n_util::GetStringUTF8(IDS_DEFAULT_ENCODING);
// TODO(crbug.com/1131016): Support Picture in Picture on WebLayer.
prefs->picture_in_picture_enabled = false;
TabImpl* tab = TabImpl::FromWebContents(web_contents);
if (tab)
tab->SetWebPreferences(prefs);
}
void ContentBrowserClientImpl::ConfigureNetworkContextParams(
content::BrowserContext* context,
bool in_memory,
const base::FilePath& relative_partition_path,
network::mojom::NetworkContextParams* context_params,
cert_verifier::mojom::CertVerifierCreationParams*
cert_verifier_creation_params) {
SystemNetworkContextManager::ConfigureDefaultNetworkContextParams(
context_params, GetUserAgent());
// Headers coming from the embedder are implicitly trusted and should not
// trigger CORS checks.
context_params->allow_any_cors_exempt_header_for_browser = true;
context_params->accept_language = GetAcceptLangs(context);
if (!context->IsOffTheRecord()) {
context_params->file_paths = network::mojom::NetworkContextFilePaths::New();
context_params->file_paths->data_directory = context->GetPath();
context_params->file_paths->cookie_database_name =
base::FilePath(FILE_PATH_LITERAL("Cookies"));
context_params->http_cache_directory =
ProfileImpl::GetCachePath(context).Append(FILE_PATH_LITERAL("Cache"));
}
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(::switches::kProxyServer)) {
std::string proxy_server =
command_line->GetSwitchValueASCII(::switches::kProxyServer);
net::ProxyConfig proxy_config;
proxy_config.proxy_rules().ParseFromString(proxy_server);
if (command_line->HasSwitch(::switches::kProxyBypassList)) {
std::string bypass_list =
command_line->GetSwitchValueASCII(::switches::kProxyBypassList);
proxy_config.proxy_rules().bypass_rules.ParseFromString(bypass_list);
}
context_params->initial_proxy_config = net::ProxyConfigWithAnnotation(
proxy_config,
net::DefineNetworkTrafficAnnotation("undefined", "Nothing here yet."));
}
if (command_line->HasSwitch(embedder_support::kShortReportingDelay)) {
context_params->reporting_delivery_interval = base::Milliseconds(100);
}
}
void ContentBrowserClientImpl::OnNetworkServiceCreated(
network::mojom::NetworkService* network_service) {
if (!SystemNetworkContextManager::HasInstance())
SystemNetworkContextManager::CreateInstance(
embedder_support::GetUserAgent());
SystemNetworkContextManager::GetInstance()->OnNetworkServiceCreated(
network_service);
}
std::vector<std::unique_ptr<blink::URLLoaderThrottle>>
ContentBrowserClientImpl::CreateURLLoaderThrottles(
const network::ResourceRequest& request,
content::BrowserContext* browser_context,
const base::RepeatingCallback<content::WebContents*()>& wc_getter,
content::NavigationUIData* navigation_ui_data,
int frame_tree_node_id) {
std::vector<std::unique_ptr<blink::URLLoaderThrottle>> result;
if (base::FeatureList::IsEnabled(features::kWebLayerSafeBrowsing) &&
IsSafebrowsingSupported()) {
#if BUILDFLAG(IS_ANDROID)
BrowserContextImpl* browser_context_impl =
static_cast<BrowserContextImpl*>(browser_context);
bool is_safe_browsing_enabled = safe_browsing::IsSafeBrowsingEnabled(
*browser_context_impl->pref_service());
if (is_safe_browsing_enabled) {
bool is_real_time_lookup_enabled =
safe_browsing::RealTimePolicyEngine::CanPerformFullURLLookup(
browser_context_impl->pref_service(),
browser_context_impl->IsOffTheRecord(),
FeatureListCreator::GetInstance()->variations_service());
// |url_lookup_service| is used when real time url check is enabled.
safe_browsing::RealTimeUrlLookupServiceBase* url_lookup_service =
is_real_time_lookup_enabled
? RealTimeUrlLookupServiceFactory::GetForBrowserContext(
browser_context)
: nullptr;
result.push_back(GetSafeBrowsingService()->CreateURLLoaderThrottle(
wc_getter, frame_tree_node_id, url_lookup_service));
}
#endif
}
auto signin_throttle =
SigninURLLoaderThrottle::Create(browser_context, wc_getter);
if (signin_throttle)
result.push_back(std::move(signin_throttle));
// Create prerender URL throttle.
auto* web_contents = wc_getter.Run();
auto* no_state_prefetch_contents =
NoStatePrefetchContentsFromWebContents(web_contents);
if (no_state_prefetch_contents) {
result.push_back(std::make_unique<prerender::PrerenderURLLoaderThrottle>(
prerender::PrerenderHistograms::GetHistogramPrefix(
no_state_prefetch_contents->origin()),
GetPrerenderCanceler(web_contents)));
}
return result;
}
bool ContentBrowserClientImpl::IsHandledURL(const GURL& url) {
if (!url.is_valid()) {
// WebLayer handles error cases.
return true;
}
std::string scheme = url.scheme();
DCHECK_EQ(scheme, base::ToLowerASCII(scheme));
static const char* const kProtocolList[] = {
url::kHttpScheme,
url::kHttpsScheme,
#if BUILDFLAG(ENABLE_WEBSOCKETS)
url::kWsScheme,
url::kWssScheme,
#endif // BUILDFLAG(ENABLE_WEBSOCKETS)
url::kFileScheme,
content::kChromeDevToolsScheme,
content::kChromeUIScheme,
content::kChromeUIUntrustedScheme,
url::kDataScheme,
#if BUILDFLAG(IS_ANDROID)
url::kContentScheme,
#endif // BUILDFLAG(IS_ANDROID)
url::kAboutScheme,
url::kBlobScheme,
url::kFileSystemScheme,
};
for (const char* supported_protocol : kProtocolList) {
if (scheme == supported_protocol)
return true;
}
return false;
}
std::vector<url::Origin>
ContentBrowserClientImpl::GetOriginsRequiringDedicatedProcess() {
return site_isolation::GetBrowserSpecificBuiltInIsolatedOrigins();
}
bool ContentBrowserClientImpl::MayReuseHost(
content::RenderProcessHost* process_host) {
// If there is currently a no-state prefetcher in progress for the host
// provided, it may not be shared. We require prefetchers to be by themselves
// in a separate process so that we can monitor their resource usage.
prerender::NoStatePrefetchManager* no_state_prefetch_manager =
NoStatePrefetchManagerFactory::GetForBrowserContext(
process_host->GetBrowserContext());
if (no_state_prefetch_manager &&
!no_state_prefetch_manager->MayReuseProcessHost(process_host)) {
return false;
}
return true;
}
void ContentBrowserClientImpl::OverridePageVisibilityState(
content::RenderFrameHost* render_frame_host,
content::PageVisibilityState* visibility_state) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(render_frame_host);
DCHECK(web_contents);
prerender::NoStatePrefetchManager* no_state_prefetch_manager =
NoStatePrefetchManagerFactory::GetForBrowserContext(
web_contents->GetBrowserContext());
if (no_state_prefetch_manager &&
no_state_prefetch_manager->IsWebContentsPrefetching(web_contents)) {
*visibility_state = content::PageVisibilityState::kHiddenButPainting;
}
}
bool ContentBrowserClientImpl::ShouldDisableSiteIsolation(
content::SiteIsolationMode site_isolation_mode) {
return site_isolation::SiteIsolationPolicy::
ShouldDisableSiteIsolationDueToMemoryThreshold(site_isolation_mode);
}
std::vector<std::string>
ContentBrowserClientImpl::GetAdditionalSiteIsolationModes() {
if (site_isolation::SiteIsolationPolicy::IsIsolationForPasswordSitesEnabled())
return {"Isolate Password Sites"};
return {};
}
void ContentBrowserClientImpl::PersistIsolatedOrigin(
content::BrowserContext* context,
const url::Origin& origin,
content::ChildProcessSecurityPolicy::IsolatedOriginSource source) {
site_isolation::SiteIsolationPolicy::PersistIsolatedOrigin(context, origin,
source);
}
base::OnceClosure ContentBrowserClientImpl::SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList client_certs,
std::unique_ptr<content::ClientCertificateDelegate> delegate) {
#if BUILDFLAG(IS_ANDROID)
return browser_ui::ShowSSLClientCertificateSelector(
web_contents, cert_request_info, std::move(delegate));
#else
delegate->ContinueWithCertificate(nullptr, nullptr);
return base::OnceClosure();
#endif
}
bool ContentBrowserClientImpl::CanCreateWindow(
content::RenderFrameHost* opener,
const GURL& opener_url,
const GURL& opener_top_level_frame_url,
const url::Origin& source_origin,
content::mojom::WindowContainerType container_type,
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features,
bool user_gesture,
bool opener_suppressed,
bool* no_javascript_access) {
*no_javascript_access = false;
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(opener);
// Block popups if there is no NewTabDelegate.
TabImpl* tab = TabImpl::FromWebContents(web_contents);
if (!tab || !tab->has_new_tab_delegate())
return false;
if (container_type == content::mojom::WindowContainerType::BACKGROUND ||
container_type == content::mojom::WindowContainerType::PERSISTENT) {
// WebLayer does not support extensions/apps, which are the only permitted
// users of background windows.
return false;
}
// 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:
[[fallthrough]];
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
[[fallthrough]];
case WindowOpenDisposition::NEW_POPUP:
[[fallthrough]];
case WindowOpenDisposition::NEW_WINDOW:
break;
default:
return false;
}
GURL popup_url(target_url);
opener->GetProcess()->FilterURL(false, &popup_url);
// Use ui::PAGE_TRANSITION_LINK to match the similar logic in //chrome.
content::OpenURLParams params(popup_url, referrer, disposition,
ui::PAGE_TRANSITION_LINK,
/*is_renderer_initiated*/ true);
params.user_gesture = user_gesture;
params.initiator_origin = source_origin;
params.source_render_frame_id = opener->GetRoutingID();
params.source_render_process_id = opener->GetProcess()->GetID();
params.source_site_instance = opener->GetSiteInstance();
// The content::OpenURLParams are created just for the delegate, and do not
// correspond to actual params created by //content, so pass null for the
// |open_url_params| argument here.
return blocked_content::MaybeBlockPopup(
web_contents, &opener_top_level_frame_url,
std::make_unique<PopupNavigationDelegateImpl>(params, web_contents,
opener),
/*open_url_params*/ nullptr, features,
HostContentSettingsMapFactory::GetForBrowserContext(
web_contents->GetBrowserContext())) != nullptr;
}
content::ControllerPresentationServiceDelegate*
ContentBrowserClientImpl::GetControllerPresentationServiceDelegate(
content::WebContents* web_contents) {
#if BUILDFLAG(IS_ANDROID)
if (WebLayerFactoryImplAndroid::GetClientMajorVersion() < 88)
return nullptr;
if (MediaRouterFactory::IsFeatureEnabled()) {
MediaRouterFactory::DoPlatformInitIfNeeded();
return media_router::PresentationServiceDelegateImpl::
GetOrCreateForWebContents(web_contents);
}
#endif
return nullptr;
}
void ContentBrowserClientImpl::OpenURL(
content::SiteInstance* site_instance,
const content::OpenURLParams& params,
base::OnceCallback<void(content::WebContents*)> callback) {
std::move(callback).Run(
ProfileImpl::FromBrowserContext(site_instance->GetBrowserContext())
->OpenUrl(params));
}
std::vector<std::unique_ptr<content::NavigationThrottle>>
ContentBrowserClientImpl::CreateThrottlesForNavigation(
content::NavigationHandle* handle) {
std::vector<std::unique_ptr<content::NavigationThrottle>> throttles;
TabImpl* tab = TabImpl::FromWebContents(handle->GetWebContents());
NavigationControllerImpl* navigation_controller = nullptr;
if (tab) {
navigation_controller =
static_cast<NavigationControllerImpl*>(tab->GetNavigationController());
}
NavigationImpl* navigation_impl = nullptr;
if (navigation_controller) {
navigation_impl =
navigation_controller->GetNavigationImplFromHandle(handle);
}
if (handle->IsInMainFrame()) {
NavigationUIDataImpl* navigation_ui_data =
static_cast<NavigationUIDataImpl*>(handle->GetNavigationUIData());
if ((!navigation_ui_data ||
!navigation_ui_data->disable_network_error_auto_reload()) &&
(!navigation_impl ||
!navigation_impl->disable_network_error_auto_reload()) &&
IsNetworkErrorAutoReloadEnabled()) {
auto auto_reload_throttle =
error_page::NetErrorAutoReloader::MaybeCreateThrottleFor(handle);
if (auto_reload_throttle)
throttles.push_back(std::move(auto_reload_throttle));
}
// MetricsNavigationThrottle requires that it runs before
// NavigationThrottles that may delay or cancel navigations, so only
// NavigationThrottles that don't delay or cancel navigations (e.g.
// throttles that are only observing callbacks without affecting navigation
// behavior) should be added before MetricsNavigationThrottle.
throttles.push_back(
page_load_metrics::MetricsNavigationThrottle::Create(handle));
if (TabImpl::FromWebContents(handle->GetWebContents())) {
throttles.push_back(
std::make_unique<NavigationErrorNavigationThrottle>(handle));
}
}
// The next highest priority throttle *must* be this as it's responsible for
// calling to NavigationController for certain events.
if (tab) {
auto throttle = navigation_controller->CreateNavigationThrottle(handle);
if (throttle)
throttles.push_back(std::move(throttle));
}
throttles.push_back(std::make_unique<SSLErrorNavigationThrottle>(
handle, std::make_unique<SSLCertReporterImpl>(),
base::BindOnce(&HandleSSLErrorWrapper), base::BindOnce(&IsInHostedApp),
base::BindOnce(
&ShouldIgnoreInterstitialBecauseNavigationDefaultedToHttps)));
std::unique_ptr<security_interstitials::InsecureFormNavigationThrottle>
insecure_form_throttle = security_interstitials::
InsecureFormNavigationThrottle::MaybeCreateNavigationThrottle(
handle, std::make_unique<WebLayerSecurityBlockingPageFactory>(),
nullptr);
if (insecure_form_throttle) {
throttles.push_back(std::move(insecure_form_throttle));
}
if (auto* throttle_manager =
subresource_filter::ContentSubresourceFilterThrottleManager::
FromNavigationHandle(*handle)) {
throttle_manager->MaybeAppendNavigationThrottles(handle, &throttles);
}
#if BUILDFLAG(IS_ANDROID)
if (IsSafebrowsingSupported()) {
std::unique_ptr<content::NavigationThrottle> safe_browsing_throttle =
GetSafeBrowsingService()->MaybeCreateSafeBrowsingNavigationThrottleFor(
handle);
if (safe_browsing_throttle)
throttles.push_back(std::move(safe_browsing_throttle));
}
if (!navigation_impl || !navigation_impl->disable_intent_processing()) {
std::unique_ptr<content::NavigationThrottle> intercept_navigation_throttle =
navigation_interception::InterceptNavigationDelegate::
MaybeCreateThrottleFor(
handle, navigation_interception::SynchronyMode::kAsync);
if (intercept_navigation_throttle)
throttles.push_back(std::move(intercept_navigation_throttle));
}
#endif
return throttles;
}
content::GeneratedCodeCacheSettings
ContentBrowserClientImpl::GetGeneratedCodeCacheSettings(
content::BrowserContext* context) {
DCHECK(context);
// If we pass 0 for size, disk_cache will pick a default size using the
// heuristics based on available disk size. These are implemented in
// disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc.
return content::GeneratedCodeCacheSettings(
true, 0, ProfileImpl::GetCachePath(context));
}
void ContentBrowserClientImpl::
RegisterAssociatedInterfaceBindersForRenderFrameHost(
content::RenderFrameHost& render_frame_host,
blink::AssociatedInterfaceRegistry& associated_registry) {
// TODO(https://crbug.com/1265864): Move the registry logic below to a
// dedicated file to ensure security review coverage.
// TODO(lingqi): Swap the parameters so that lambda functions are not needed.
associated_registry.AddInterface<autofill::mojom::AutofillDriver>(
base::BindRepeating(
[](content::RenderFrameHost* render_frame_host,
mojo::PendingAssociatedReceiver<autofill::mojom::AutofillDriver>
receiver) {
autofill::ContentAutofillDriverFactory::BindAutofillDriver(
std::move(receiver), render_frame_host);
},
&render_frame_host));
associated_registry.AddInterface<autofill::mojom::PasswordManagerDriver>(
base::BindRepeating(
[](content::RenderFrameHost* render_frame_host,
mojo::PendingAssociatedReceiver<
autofill::mojom::PasswordManagerDriver> receiver) {
PasswordManagerDriverFactory::BindPasswordManagerDriver(
std::move(receiver), render_frame_host);
},
&render_frame_host));
associated_registry.AddInterface<
content_capture::mojom::ContentCaptureReceiver>(base::BindRepeating(
[](content::RenderFrameHost* render_frame_host,
mojo::PendingAssociatedReceiver<
content_capture::mojom::ContentCaptureReceiver> receiver) {
content_capture::OnscreenContentProvider::BindContentCaptureReceiver(
std::move(receiver), render_frame_host);
},
&render_frame_host));
associated_registry.AddInterface<page_load_metrics::mojom::PageLoadMetrics>(
base::BindRepeating(
[](content::RenderFrameHost* render_frame_host,
mojo::PendingAssociatedReceiver<
page_load_metrics::mojom::PageLoadMetrics> receiver) {
page_load_metrics::MetricsWebContentsObserver::BindPageLoadMetrics(
std::move(receiver), render_frame_host);
},
&render_frame_host));
associated_registry.AddInterface<
security_interstitials::mojom::InterstitialCommands>(base::BindRepeating(
[](content::RenderFrameHost* render_frame_host,
mojo::PendingAssociatedReceiver<
security_interstitials::mojom::InterstitialCommands> receiver) {
security_interstitials::SecurityInterstitialTabHelper::
BindInterstitialCommands(std::move(receiver), render_frame_host);
},
&render_frame_host));
associated_registry.AddInterface<
subresource_filter::mojom::SubresourceFilterHost>(base::BindRepeating(
[](content::RenderFrameHost* render_frame_host,
mojo::PendingAssociatedReceiver<
subresource_filter::mojom::SubresourceFilterHost> receiver) {
subresource_filter::ContentSubresourceFilterThrottleManager::
BindReceiver(std::move(receiver), render_frame_host);
},
&render_frame_host));
}
void ContentBrowserClientImpl::ExposeInterfacesToRenderer(
service_manager::BinderRegistry* registry,
blink::AssociatedInterfaceRegistry* associated_registry,
content::RenderProcessHost* render_process_host) {
performance_manager::PerformanceManagerRegistry::GetInstance()
->CreateProcessNodeAndExposeInterfacesToRendererProcess(
registry, render_process_host);
#if BUILDFLAG(IS_ANDROID)
auto create_spellcheck_host =
[](mojo::PendingReceiver<spellcheck::mojom::SpellCheckHost> receiver) {
mojo::MakeSelfOwnedReceiver(std::make_unique<SpellCheckHostImpl>(),
std::move(receiver));
};
registry->AddInterface<spellcheck::mojom::SpellCheckHost>(
base::BindRepeating(create_spellcheck_host),
content::GetUIThreadTaskRunner({}));
if (base::FeatureList::IsEnabled(features::kWebLayerSafeBrowsing) &&
IsSafebrowsingSupported()) {
GetSafeBrowsingService()->AddInterface(registry, render_process_host);
}
#endif // BUILDFLAG(IS_ANDROID)
}
void ContentBrowserClientImpl::BindMediaServiceReceiver(
content::RenderFrameHost* render_frame_host,
mojo::GenericPendingReceiver receiver) {
#if BUILDFLAG(IS_ANDROID)
if (auto r = receiver.As<media::mojom::MediaDrmStorage>()) {
CreateMediaDrmStorage(render_frame_host, std::move(r));
return;
}
#endif
}
void ContentBrowserClientImpl::RegisterBrowserInterfaceBindersForFrame(
content::RenderFrameHost* render_frame_host,
mojo::BinderMapWithContext<content::RenderFrameHost*>* map) {
PopulateWebLayerFrameBinders(render_frame_host, map);
performance_manager::PerformanceManagerRegistry::GetInstance()
->ExposeInterfacesToRenderFrame(map);
}
void ContentBrowserClientImpl::RenderProcessWillLaunch(
content::RenderProcessHost* host) {
#if BUILDFLAG(IS_ANDROID)
host->AddFilter(new cdm::CdmMessageFilterAndroid(
!host->GetBrowserContext()->IsOffTheRecord(),
/*force_to_support_secure_codecs*/ false));
#endif
PageSpecificContentSettingsDelegate::InitializeRenderer(host);
}
void ContentBrowserClientImpl::CreateFeatureListAndFieldTrials() {
local_state_ = CreateLocalState();
feature_list_creator_ =
std::make_unique<FeatureListCreator>(local_state_.get());
if (!SystemNetworkContextManager::HasInstance())
SystemNetworkContextManager::CreateInstance(GetUserAgent());
feature_list_creator_->SetSystemNetworkContextManager(
SystemNetworkContextManager::GetInstance());
feature_list_creator_->CreateFeatureListAndFieldTrials();
}
#if BUILDFLAG(IS_ANDROID)
SafeBrowsingService* ContentBrowserClientImpl::GetSafeBrowsingService() {
return BrowserProcess::GetInstance()->GetSafeBrowsingService();
}
#endif
// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) || \
BUILDFLAG(IS_ANDROID)
void ContentBrowserClientImpl::GetAdditionalMappedFilesForChildProcess(
const base::CommandLine& command_line,
int child_process_id,
content::PosixFileDescriptorInfo* mappings) {
#if BUILDFLAG(IS_ANDROID)
base::MemoryMappedFile::Region region;
int fd = ui::GetMainAndroidPackFd(®ion);
mappings->ShareWithRegion(kWebLayerMainPakDescriptor, fd, region);
fd = ui::GetCommonResourcesPackFd(®ion);
mappings->ShareWithRegion(kWebLayer100PercentPakDescriptor, fd, region);
fd = ui::GetLocalePackFd(®ion);
mappings->ShareWithRegion(kWebLayerLocalePakDescriptor, fd, region);
if (base::android::BundleUtils::IsBundle()) {
fd = ui::GetSecondaryLocalePackFd(®ion);
mappings->ShareWithRegion(kWebLayerSecondaryLocalePakDescriptor, fd,
region);
} else {
mappings->ShareWithRegion(kWebLayerSecondaryLocalePakDescriptor,
base::GlobalDescriptors::GetInstance()->Get(
kWebLayerSecondaryLocalePakDescriptor),
base::GlobalDescriptors::GetInstance()->GetRegion(
kWebLayerSecondaryLocalePakDescriptor));
}
int crash_signal_fd =
crashpad::CrashHandlerHost::Get()->GetDeathSignalSocket();
if (crash_signal_fd >= 0)
mappings->Share(kCrashDumpSignal, crash_signal_fd);
#endif // BUILDFLAG(IS_ANDROID)
}
#endif
void ContentBrowserClientImpl::AppendExtraCommandLineSwitches(
base::CommandLine* command_line,
int child_process_id) {
const base::CommandLine& browser_command_line(
*base::CommandLine::ForCurrentProcess());
std::string process_type =
command_line->GetSwitchValueASCII(::switches::kProcessType);
if (process_type == ::switches::kRendererProcess) {
// Please keep this in alphabetical order.
static const char* const kSwitchNames[] = {
embedder_support::kOriginTrialDisabledFeatures,
embedder_support::kOriginTrialDisabledTokens,
embedder_support::kOriginTrialPublicKey,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
std::size(kSwitchNames));
}
}
// static
std::unique_ptr<PrefService> ContentBrowserClientImpl::CreateLocalState() {
auto pref_registry = base::MakeRefCounted<PrefRegistrySimple>();
RegisterPrefs(pref_registry.get());
base::FilePath path;
CHECK(base::PathService::Get(DIR_USER_DATA, &path));
path = path.AppendASCII("Local State");
PrefServiceFactory pref_service_factory;
pref_service_factory.set_user_prefs(
base::MakeRefCounted<JsonPrefStore>(path));
{
// Creating the prefs service may require reading the preferences from
// disk.
base::ScopedAllowBlocking allow_io;
return pref_service_factory.Create(pref_registry);
}
}
#if BUILDFLAG(IS_ANDROID)
bool ContentBrowserClientImpl::WillCreateURLLoaderFactory(
content::BrowserContext* browser_context,
content::RenderFrameHost* frame,
int render_process_id,
URLLoaderFactoryType type,
const url::Origin& request_initiator,
absl::optional<int64_t> navigation_id,
ukm::SourceIdObj ukm_source_id,
mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver,
mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>*
header_client,
bool* bypass_redirect_checks,
bool* disable_secure_dns,
network::mojom::URLLoaderFactoryOverridePtr* factory_override) {
// The navigation API intercepting API only supports main frame navigations.
if (type != URLLoaderFactoryType::kNavigation || frame->GetParent())
return false;
auto* web_contents = content::WebContents::FromRenderFrameHost(frame);
TabImpl* tab = TabImpl::FromWebContents(web_contents);
if (!tab)
return false;
auto* navigation_controller =
static_cast<NavigationControllerImpl*>(tab->GetNavigationController());
auto* navigation_impl =
navigation_controller->GetNavigationImplFromId(*navigation_id);
if (!navigation_impl)
return false;
auto response = navigation_impl->TakeResponse();
if (!response && !ProxyingURLLoaderFactoryImpl::HasCachedInputStream(
frame->GetFrameTreeNodeId(),
navigation_impl->navigation_entry_unique_id())) {
return false;
}
mojo::PendingReceiver<network::mojom::URLLoaderFactory> proxied_receiver =
std::move(*factory_receiver);
mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote;
*factory_receiver = target_factory_remote.InitWithNewPipeAndPassReceiver();
// Owns itself.
new ProxyingURLLoaderFactoryImpl(
std::move(proxied_receiver), std::move(target_factory_remote),
navigation_impl->GetURL(), std::move(response),
frame->GetFrameTreeNodeId(),
navigation_impl->navigation_entry_unique_id());
return true;
}
content::ContentBrowserClient::WideColorGamutHeuristic
ContentBrowserClientImpl::GetWideColorGamutHeuristic() {
// Always match window since a mismatch can cause inefficiency in surface
// flinger.
return WideColorGamutHeuristic::kUseWindow;
}
std::unique_ptr<content::LoginDelegate>
ContentBrowserClientImpl::CreateLoginDelegate(
const net::AuthChallengeInfo& auth_info,
content::WebContents* web_contents,
const content::GlobalRequestID& request_id,
bool is_request_for_primary_main_frame,
const GURL& url,
scoped_refptr<net::HttpResponseHeaders> response_headers,
bool first_auth_attempt,
LoginAuthRequiredCallback auth_required_callback) {
return std::make_unique<HttpAuthHandlerImpl>(
auth_info, web_contents, first_auth_attempt,
std::move(auth_required_callback));
}
std::unique_ptr<content::TtsEnvironmentAndroid>
ContentBrowserClientImpl::CreateTtsEnvironmentAndroid() {
return std::make_unique<TtsEnvironmentAndroidImpl>();
}
bool ContentBrowserClientImpl::
ShouldObserveContainerViewLocationForDialogOverlays() {
// Observe location changes of the container view as WebLayer might be
// embedded in a scrollable container and we need to update the position of
// any DialogOverlays.
return true;
}
content::BluetoothDelegate* ContentBrowserClientImpl::GetBluetoothDelegate() {
if (!bluetooth_delegate_) {
bluetooth_delegate_ = std::make_unique<permissions::BluetoothDelegateImpl>(
std::make_unique<WebLayerBluetoothDelegateImplClient>());
}
return bluetooth_delegate_.get();
}
#endif // BUILDFLAG(IS_ANDROID)
content::SpeechRecognitionManagerDelegate*
ContentBrowserClientImpl::CreateSpeechRecognitionManagerDelegate() {
return new WebLayerSpeechRecognitionManagerDelegate();
}
bool ContentBrowserClientImpl::ShouldSandboxNetworkService() {
#if BUILDFLAG(IS_WIN)
// Weblayer ConfigureNetworkContextParams does not support data migration
// required for network sandbox to be enabled on Windows.
return false;
#else
return ContentBrowserClient::ShouldSandboxNetworkService();
#endif // BUILDFLAG(IS_WIN)
}
#if BUILDFLAG(ENABLE_ARCORE)
content::XrIntegrationClient*
ContentBrowserClientImpl::GetXrIntegrationClient() {
if (!XrIntegrationClientImpl::IsEnabled())
return nullptr;
if (!xr_integration_client_)
xr_integration_client_ = std::make_unique<XrIntegrationClientImpl>();
return xr_integration_client_.get();
}
#endif // BUILDFLAG(ENABLE_ARCORE)
ukm::UkmService* ContentBrowserClientImpl::GetUkmService() {
#if BUILDFLAG(IS_ANDROID)
return WebLayerMetricsServiceClient::GetInstance()->GetUkmService();
#else
return nullptr;
#endif
}
bool ContentBrowserClientImpl::HasErrorPage(int http_status_code) {
// Use an internal error page, if we have one for the status code.
return error_page::LocalizedError::HasStrings(
error_page::Error::kHttpErrorDomain, http_status_code);
}
bool ContentBrowserClientImpl::IsClipboardPasteAllowed(
content::RenderFrameHost* render_frame_host) {
DCHECK(render_frame_host);
content::BrowserContext* browser_context =
render_frame_host->GetBrowserContext();
DCHECK(browser_context);
content::PermissionController* permission_controller =
browser_context->GetPermissionController();
blink::mojom::PermissionStatus status =
permission_controller->GetPermissionStatusForCurrentDocument(
blink::PermissionType::CLIPBOARD_READ_WRITE, render_frame_host);
if (!render_frame_host->HasTransientUserActivation() &&
status != blink::mojom::PermissionStatus::GRANTED) {
// Paste requires either user activation, or granted web permission.
return false;
}
return true;
}
bool ContentBrowserClientImpl::ShouldPreconnectNavigation(
content::BrowserContext* browser_context) {
return true;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/content_browser_client_impl.cc | C++ | unknown | 50,307 |
// 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_CONTENT_BROWSER_CLIENT_IMPL_H_
#define WEBLAYER_BROWSER_CONTENT_BROWSER_CLIENT_IMPL_H_
#include <memory>
#include <string>
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/content_browser_client.h"
#include "device/vr/buildflags/buildflags.h"
#include "services/service_manager/public/cpp/binder_registry.h"
class PrefService;
namespace blink {
class StorageKey;
} // namespace blink
namespace net {
class SiteForCookies;
} // namespace net
namespace permissions {
class BluetoothDelegateImpl;
}
namespace weblayer {
class FeatureListCreator;
class SafeBrowsingService;
struct MainParams;
#if BUILDFLAG(ENABLE_ARCORE)
class XrIntegrationClientImpl;
#endif // BUILDFLAG(ENABLE_ARCORE)
class ContentBrowserClientImpl : public content::ContentBrowserClient {
public:
explicit ContentBrowserClientImpl(MainParams* params);
~ContentBrowserClientImpl() override;
// ContentBrowserClient overrides.
std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts(
bool is_integration_test) override;
std::string GetApplicationLocale() override;
std::string GetAcceptLangs(content::BrowserContext* context) override;
content::AllowServiceWorkerResult AllowServiceWorker(
const GURL& scope,
const net::SiteForCookies& site_for_cookies,
const absl::optional<url::Origin>& top_frame_origin,
const GURL& script_url,
content::BrowserContext* context) override;
bool AllowSharedWorker(const GURL& worker_url,
const net::SiteForCookies& site_for_cookies,
const absl::optional<url::Origin>& top_frame_origin,
const std::string& name,
const blink::StorageKey& storage_key,
content::BrowserContext* context,
int render_process_id,
int render_frame_id) override;
void AllowWorkerFileSystem(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalRenderFrameHostId>& render_frames,
base::OnceCallback<void(bool)> callback) override;
bool AllowWorkerIndexedDB(const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalRenderFrameHostId>&
render_frames) override;
bool AllowWorkerCacheStorage(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalRenderFrameHostId>& render_frames)
override;
bool AllowWorkerWebLocks(const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalRenderFrameHostId>&
render_frames) override;
std::unique_ptr<content::WebContentsViewDelegate> GetWebContentsViewDelegate(
content::WebContents* web_contents) override;
bool CanShutdownGpuProcessNowOnIOThread() override;
std::unique_ptr<content::DevToolsManagerDelegate>
CreateDevToolsManagerDelegate() override;
void LogWebFeatureForCurrentPage(content::RenderFrameHost* render_frame_host,
blink::mojom::WebFeature feature) override;
std::string GetProduct() override;
std::string GetUserAgent() override;
std::string GetFullUserAgent() override;
std::string GetReducedUserAgent() override;
blink::UserAgentMetadata GetUserAgentMetadata() override;
void OverrideWebkitPrefs(content::WebContents* web_contents,
blink::web_pref::WebPreferences* prefs) override;
void ConfigureNetworkContextParams(
content::BrowserContext* context,
bool in_memory,
const base::FilePath& relative_partition_path,
network::mojom::NetworkContextParams* network_context_params,
cert_verifier::mojom::CertVerifierCreationParams*
cert_verifier_creation_params) override;
void OnNetworkServiceCreated(
network::mojom::NetworkService* network_service) override;
std::vector<std::unique_ptr<blink::URLLoaderThrottle>>
CreateURLLoaderThrottles(
const network::ResourceRequest& request,
content::BrowserContext* browser_context,
const base::RepeatingCallback<content::WebContents*()>& wc_getter,
content::NavigationUIData* navigation_ui_data,
int frame_tree_node_id) override;
bool IsHandledURL(const GURL& url) override;
std::vector<url::Origin> GetOriginsRequiringDedicatedProcess() override;
bool MayReuseHost(content::RenderProcessHost* process_host) override;
void OverridePageVisibilityState(
content::RenderFrameHost* render_frame_host,
content::PageVisibilityState* visibility_state) override;
bool ShouldDisableSiteIsolation(
content::SiteIsolationMode site_isolation_mode) override;
std::vector<std::string> GetAdditionalSiteIsolationModes() override;
void PersistIsolatedOrigin(
content::BrowserContext* context,
const url::Origin& origin,
content::ChildProcessSecurityPolicy::IsolatedOriginSource source)
override;
base::OnceClosure SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
net::ClientCertIdentityList client_certs,
std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
bool CanCreateWindow(content::RenderFrameHost* opener,
const GURL& opener_url,
const GURL& opener_top_level_frame_url,
const url::Origin& source_origin,
content::mojom::WindowContainerType container_type,
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& features,
bool user_gesture,
bool opener_suppressed,
bool* no_javascript_access) override;
content::ControllerPresentationServiceDelegate*
GetControllerPresentationServiceDelegate(
content::WebContents* web_contents) override;
void OpenURL(
content::SiteInstance* site_instance,
const content::OpenURLParams& params,
base::OnceCallback<void(content::WebContents*)> callback) override;
std::vector<std::unique_ptr<content::NavigationThrottle>>
CreateThrottlesForNavigation(content::NavigationHandle* handle) override;
content::GeneratedCodeCacheSettings GetGeneratedCodeCacheSettings(
content::BrowserContext* context) override;
void RegisterAssociatedInterfaceBindersForRenderFrameHost(
content::RenderFrameHost& render_frame_host,
blink::AssociatedInterfaceRegistry& associated_registry) override;
void ExposeInterfacesToRenderer(
service_manager::BinderRegistry* registry,
blink::AssociatedInterfaceRegistry* associated_registry,
content::RenderProcessHost* render_process_host) override;
void BindMediaServiceReceiver(content::RenderFrameHost* render_frame_host,
mojo::GenericPendingReceiver receiver) override;
void RegisterBrowserInterfaceBindersForFrame(
content::RenderFrameHost* render_frame_host,
mojo::BinderMapWithContext<content::RenderFrameHost*>* map) override;
void BindHostReceiverForRenderer(
content::RenderProcessHost* render_process_host,
mojo::GenericPendingReceiver receiver) override;
void RenderProcessWillLaunch(content::RenderProcessHost* host) override;
// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
// complete.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) || \
BUILDFLAG(IS_ANDROID)
void GetAdditionalMappedFilesForChildProcess(
const base::CommandLine& command_line,
int child_process_id,
content::PosixFileDescriptorInfo* mappings) override;
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS) ||
// BUILDFLAG(IS_ANDROID)
void AppendExtraCommandLineSwitches(base::CommandLine* command_line,
int child_process_id) override;
#if BUILDFLAG(IS_ANDROID)
bool WillCreateURLLoaderFactory(
content::BrowserContext* browser_context,
content::RenderFrameHost* frame,
int render_process_id,
URLLoaderFactoryType type,
const url::Origin& request_initiator,
absl::optional<int64_t> navigation_id,
ukm::SourceIdObj ukm_source_id,
mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver,
mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>*
header_client,
bool* bypass_redirect_checks,
bool* disable_secure_dns,
network::mojom::URLLoaderFactoryOverridePtr* factory_override) override;
WideColorGamutHeuristic GetWideColorGamutHeuristic() override;
std::unique_ptr<content::LoginDelegate> CreateLoginDelegate(
const net::AuthChallengeInfo& auth_info,
content::WebContents* web_contents,
const content::GlobalRequestID& request_id,
bool is_request_for_primary_main_frame,
const GURL& url,
scoped_refptr<net::HttpResponseHeaders> response_headers,
bool first_auth_attempt,
LoginAuthRequiredCallback auth_required_callback) override;
std::unique_ptr<content::TtsEnvironmentAndroid> CreateTtsEnvironmentAndroid()
override;
bool ShouldObserveContainerViewLocationForDialogOverlays() override;
content::BluetoothDelegate* GetBluetoothDelegate() override;
#endif // BUILDFLAG(IS_ANDROID)
content::SpeechRecognitionManagerDelegate*
CreateSpeechRecognitionManagerDelegate() override;
bool ShouldSandboxNetworkService() override;
#if BUILDFLAG(ENABLE_ARCORE)
content::XrIntegrationClient* GetXrIntegrationClient() override;
#endif // BUILDFLAG(ENABLE_ARCORE)
ukm::UkmService* GetUkmService() override;
bool HasErrorPage(int http_status_code) override;
bool IsClipboardPasteAllowed(
content::RenderFrameHost* render_frame_host) override;
bool ShouldPreconnectNavigation(
content::BrowserContext* browser_context) override;
void CreateFeatureListAndFieldTrials();
private:
std::unique_ptr<PrefService> CreateLocalState();
#if BUILDFLAG(IS_ANDROID)
SafeBrowsingService* GetSafeBrowsingService();
std::unique_ptr<permissions::BluetoothDelegateImpl> bluetooth_delegate_;
#endif
raw_ptr<MainParams> params_;
// Local-state is created early on, before BrowserProcess. Ownership moves to
// BrowserMainParts, then BrowserProcess. BrowserProcess ultimately owns
// local-state so that it can be destroyed along with other BrowserProcess
// state.
std::unique_ptr<PrefService> local_state_;
std::unique_ptr<FeatureListCreator> feature_list_creator_;
#if BUILDFLAG(ENABLE_ARCORE)
std::unique_ptr<XrIntegrationClientImpl> xr_integration_client_;
#endif // BUILDFLAG(ENABLE_ARCORE)
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_CONTENT_BROWSER_CLIENT_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/content_browser_client_impl.h | C++ | unknown | 11,512 |
// 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.
// This file exposes services from the browser to child processes.
#include "weblayer/browser/content_browser_client_impl.h"
#include "weblayer/browser/content_settings_manager_delegate.h"
namespace weblayer {
void ContentBrowserClientImpl::BindHostReceiverForRenderer(
content::RenderProcessHost* render_process_host,
mojo::GenericPendingReceiver receiver) {
if (auto host_receiver =
receiver.As<content_settings::mojom::ContentSettingsManager>()) {
content_settings::ContentSettingsManagerImpl::Create(
render_process_host, std::move(host_receiver),
std::make_unique<ContentSettingsManagerDelegate>());
return;
}
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/content_browser_client_impl_receiver_bindings.cc | C++ | unknown | 837 |
// 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 "components/content_settings/core/browser/cookie_settings.h"
#include "content/public/test/browser_test_utils.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "weblayer/browser/cookie_settings_factory.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
constexpr char kHasLocalStorageScript[] = R"(
new Promise(function (resolve, reject) {
try {
localStorage.setItem('foo', 'bar');
resolve(true);
} catch(e) {
resolve(false);
}
})
)";
} // namespace
using ContentSettingsBrowserTest = WebLayerBrowserTest;
IN_PROC_BROWSER_TEST_F(ContentSettingsBrowserTest, LocalStorageAvailable) {
ASSERT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(embedded_test_server()->GetURL("/echo"),
shell());
content::WebContents* web_contents =
static_cast<TabImpl*>(shell()->tab())->web_contents();
EXPECT_TRUE(
content::EvalJs(web_contents, kHasLocalStorageScript).ExtractBool());
}
IN_PROC_BROWSER_TEST_F(ContentSettingsBrowserTest, LocalStorageDenied) {
ASSERT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(embedded_test_server()->GetURL("/echo"),
shell());
content::WebContents* web_contents =
static_cast<TabImpl*>(shell()->tab())->web_contents();
// Blocking cookies for this URL should also block local storage.
CookieSettingsFactory::GetForBrowserContext(web_contents->GetBrowserContext())
->SetCookieSetting(embedded_test_server()->base_url(),
CONTENT_SETTING_BLOCK);
EXPECT_FALSE(
content::EvalJs(web_contents, kHasLocalStorageScript).ExtractBool());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/content_settings_browsertest.cc | C++ | unknown | 2,037 |
// 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/content_settings_manager_delegate.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "weblayer/browser/cookie_settings_factory.h"
namespace weblayer {
ContentSettingsManagerDelegate::ContentSettingsManagerDelegate() = default;
ContentSettingsManagerDelegate::~ContentSettingsManagerDelegate() = default;
scoped_refptr<content_settings::CookieSettings>
ContentSettingsManagerDelegate::GetCookieSettings(
content::BrowserContext* browser_context) {
return CookieSettingsFactory::GetForBrowserContext(browser_context);
}
bool ContentSettingsManagerDelegate::AllowStorageAccess(
int render_process_id,
int render_frame_id,
content_settings::mojom::ContentSettingsManager::StorageType storage_type,
const GURL& url,
bool allowed,
base::OnceCallback<void(bool)>* callback) {
return false;
}
std::unique_ptr<content_settings::ContentSettingsManagerImpl::Delegate>
ContentSettingsManagerDelegate::Clone() {
return std::make_unique<ContentSettingsManagerDelegate>();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/content_settings_manager_delegate.cc | C++ | unknown | 1,229 |
// 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_CONTENT_SETTINGS_MANAGER_DELEGATE_H_
#define WEBLAYER_BROWSER_CONTENT_SETTINGS_MANAGER_DELEGATE_H_
#include "components/content_settings/browser/content_settings_manager_impl.h"
namespace weblayer {
class ContentSettingsManagerDelegate
: public content_settings::ContentSettingsManagerImpl::Delegate {
public:
ContentSettingsManagerDelegate();
~ContentSettingsManagerDelegate() override;
private:
// content_settings::ContentSettingsManagerImpl::Delegate:
scoped_refptr<content_settings::CookieSettings> GetCookieSettings(
content::BrowserContext* browser_context) override;
bool AllowStorageAccess(
int render_process_id,
int render_frame_id,
content_settings::mojom::ContentSettingsManager::StorageType storage_type,
const GURL& url,
bool allowed,
base::OnceCallback<void(bool)>* callback) override;
std::unique_ptr<Delegate> Clone() override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_CONTENT_SETTINGS_MANAGER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/content_settings_manager_delegate.h | C++ | unknown | 1,174 |
// 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/browser/content_view_render_view.h"
#include <android/bitmap.h>
#include <memory>
#include <utility>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "cc/slim/layer.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/android/resources/resource_manager.h"
#include "ui/android/view_android.h"
#include "ui/android/window_android.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/geometry/size.h"
#include "weblayer/browser/java/jni/ContentViewRenderView_jni.h"
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
ContentViewRenderView::ContentViewRenderView(JNIEnv* env,
jobject obj,
gfx::NativeWindow root_window)
: root_window_(root_window) {
java_obj_.Reset(env, obj);
}
ContentViewRenderView::~ContentViewRenderView() {
DCHECK(content_height_changed_listener_.is_null());
}
void ContentViewRenderView::SetContentHeightChangedListener(
base::RepeatingClosure callback) {
DCHECK(content_height_changed_listener_.is_null() || callback.is_null());
content_height_changed_listener_ = std::move(callback);
}
// static
static jlong JNI_ContentViewRenderView_Init(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
const JavaParamRef<jobject>& jroot_window_android) {
gfx::NativeWindow root_window =
ui::WindowAndroid::FromJavaWindowAndroid(jroot_window_android);
ContentViewRenderView* content_view_render_view =
new ContentViewRenderView(env, obj, root_window);
return reinterpret_cast<intptr_t>(content_view_render_view);
}
void ContentViewRenderView::Destroy(JNIEnv* env) {
delete this;
}
void ContentViewRenderView::SetCurrentWebContents(
JNIEnv* env,
const JavaParamRef<jobject>& jweb_contents) {
InitCompositor();
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(jweb_contents);
if (web_contents_)
web_contents_->SetPageBaseBackgroundColor(absl::nullopt);
if (web_contents_layer_)
web_contents_layer_->RemoveFromParent();
web_contents_ = web_contents;
web_contents_layer_ = web_contents ? web_contents->GetNativeView()->GetLayer()
: scoped_refptr<cc::slim::Layer>();
UpdateWebContentsBaseBackgroundColor();
if (web_contents_layer_)
root_container_layer_->AddChild(web_contents_layer_);
}
void ContentViewRenderView::OnViewportSizeChanged(JNIEnv* env,
jint width,
jint height) {
bool content_height_changed = content_height_ != height;
content_height_ = height;
if (content_height_changed && !content_height_changed_listener_.is_null())
content_height_changed_listener_.Run();
}
void ContentViewRenderView::OnPhysicalBackingSizeChanged(
JNIEnv* env,
const JavaParamRef<jobject>& jweb_contents,
jint width,
jint height,
jboolean for_config_change) {
content::WebContents* web_contents =
content::WebContents::FromJavaWebContents(jweb_contents);
gfx::Size size(width, height);
// The default resize timeout on Android is 1s. It was chosen with browser
// use case in mind where resize is rare (eg orientation change, fullscreen)
// and users are generally willing to wait for those cases instead of seeing
// a frame at the wrong size. Weblayer currently can be resized while user
// is interacting with the page, in which case the timeout is too long.
// For now, use the default long timeout only for rotation (ie config change)
// and just use a zero timeout for all other cases.
absl::optional<base::TimeDelta> override_deadline;
if (!for_config_change)
override_deadline = base::TimeDelta();
web_contents->GetNativeView()->OnPhysicalBackingSizeChanged(
size, override_deadline);
}
void ContentViewRenderView::SurfaceCreated(JNIEnv* env) {
InitCompositor();
}
void ContentViewRenderView::SurfaceDestroyed(JNIEnv* env,
jboolean cache_back_buffer) {
if (cache_back_buffer)
compositor_->CacheBackBufferForCurrentSurface();
// When we switch from Chrome to other app we can't detach child surface
// controls because it leads to a visible hole: b/157439199. To avoid this we
// don't detach surfaces if the surface is going to be destroyed, they will be
// detached and freed by OS.
compositor_->PreserveChildSurfaceControls();
compositor_->SetSurface(nullptr, false);
}
void ContentViewRenderView::SurfaceChanged(
JNIEnv* env,
jboolean can_be_used_with_surface_control,
jint width,
jint height,
jboolean transparent_background,
const JavaParamRef<jobject>& new_surface) {
use_transparent_background_ = transparent_background;
UpdateWebContentsBaseBackgroundColor();
compositor_->SetRequiresAlphaChannel(use_transparent_background_);
// Java side will pass a null `new_surface` if the surface did not change.
if (new_surface) {
compositor_->SetSurface(new_surface, can_be_used_with_surface_control);
}
compositor_->SetWindowBounds(gfx::Size(width, height));
}
void ContentViewRenderView::SetNeedsRedraw(JNIEnv* env) {
if (compositor_) {
compositor_->SetNeedsRedraw();
}
}
base::android::ScopedJavaLocalRef<jobject>
ContentViewRenderView::GetResourceManager(JNIEnv* env) {
return compositor_->GetResourceManager().GetJavaObject();
}
void ContentViewRenderView::UpdateBackgroundColor(JNIEnv* env) {
if (!compositor_)
return;
compositor_->SetBackgroundColor(
requires_alpha_channel_
? SK_ColorTRANSPARENT
: Java_ContentViewRenderView_getBackgroundColor(env, java_obj_));
}
void ContentViewRenderView::SetRequiresAlphaChannel(
JNIEnv* env,
jboolean requires_alpha_channel) {
requires_alpha_channel_ = requires_alpha_channel;
UpdateBackgroundColor(env);
}
void ContentViewRenderView::SetDidSwapBuffersCallbackEnabled(JNIEnv* env,
jboolean enable) {
InitCompositor();
compositor_->SetDidSwapBuffersCallbackEnabled(enable);
}
void ContentViewRenderView::UpdateLayerTreeHost() {
// TODO(wkorman): Rename Layout to UpdateLayerTreeHost in all Android
// Compositor related classes.
}
void ContentViewRenderView::DidSwapFrame(int pending_frames) {
JNIEnv* env = base::android::AttachCurrentThread();
TRACE_EVENT0("weblayer", "Java_ContentViewRenderView_didSwapFrame");
if (Java_ContentViewRenderView_didSwapFrame(env, java_obj_)) {
compositor_->SetNeedsRedraw();
}
}
void ContentViewRenderView::DidSwapBuffers(const gfx::Size& swap_size) {
JNIEnv* env = base::android::AttachCurrentThread();
bool matches_window_bounds = swap_size == compositor_->GetWindowBounds();
Java_ContentViewRenderView_didSwapBuffers(env, java_obj_,
matches_window_bounds);
}
void ContentViewRenderView::EvictCachedSurface(JNIEnv* env) {
compositor_->EvictCachedBackBuffer();
}
void ContentViewRenderView::InitCompositor() {
if (compositor_)
return;
compositor_.reset(content::Compositor::Create(this, root_window_));
root_container_layer_ = cc::slim::Layer::Create();
root_container_layer_->SetIsDrawable(false);
compositor_->SetRootLayer(root_container_layer_);
UpdateBackgroundColor(base::android::AttachCurrentThread());
}
void ContentViewRenderView::UpdateWebContentsBaseBackgroundColor() {
if (!web_contents_)
return;
web_contents_->SetPageBaseBackgroundColor(
use_transparent_background_ ? absl::make_optional(SK_ColorTRANSPARENT)
: absl::nullopt);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/content_view_render_view.cc | C++ | unknown | 8,493 |
// 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.
#ifndef WEBLAYER_BROWSER_CONTENT_VIEW_RENDER_VIEW_H_
#define WEBLAYER_BROWSER_CONTENT_VIEW_RENDER_VIEW_H_
#include <memory>
#include "base/android/jni_weak_ref.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "content/public/browser/android/compositor_client.h"
#include "ui/gfx/native_widget_types.h"
namespace cc::slim {
class Layer;
}
namespace content {
class Compositor;
class WebContents;
} // namespace content
namespace weblayer {
class ContentViewRenderView : public content::CompositorClient {
public:
ContentViewRenderView(JNIEnv* env,
jobject obj,
gfx::NativeWindow root_window);
ContentViewRenderView(const ContentViewRenderView&) = delete;
ContentViewRenderView& operator=(const ContentViewRenderView&) = delete;
content::Compositor* compositor() { return compositor_.get(); }
scoped_refptr<cc::slim::Layer> root_container_layer() {
return root_container_layer_;
}
// Content Height, in pixels.
int content_height() const { return content_height_; }
void SetContentHeightChangedListener(base::RepeatingClosure callback);
// Methods called from Java via JNI -----------------------------------------
void Destroy(JNIEnv* env);
void SetCurrentWebContents(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& jweb_contents);
void OnPhysicalBackingSizeChanged(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& jweb_contents,
jint width,
jint height,
jboolean for_config_change);
void OnViewportSizeChanged(JNIEnv* env, jint width, jint height);
void SurfaceCreated(JNIEnv* env);
void SurfaceDestroyed(JNIEnv* env, jboolean cache_back_buffer);
void SurfaceChanged(JNIEnv* env,
jboolean can_be_used_with_surface_control,
jint width,
jint height,
jboolean transparent_background,
const base::android::JavaParamRef<jobject>& new_surface);
void SetNeedsRedraw(JNIEnv* env);
void EvictCachedSurface(JNIEnv* env);
base::android::ScopedJavaLocalRef<jobject> GetResourceManager(JNIEnv* env);
void UpdateBackgroundColor(JNIEnv* env);
void SetRequiresAlphaChannel(JNIEnv* env, jboolean requires_alpha_channel);
void SetDidSwapBuffersCallbackEnabled(JNIEnv* env, jboolean enable);
// CompositorClient implementation
void UpdateLayerTreeHost() override;
void DidSwapFrame(int pending_frames) override;
void DidSwapBuffers(const gfx::Size& swap_size) override;
private:
~ContentViewRenderView() override;
void InitCompositor();
void UpdateWebContentsBaseBackgroundColor();
base::android::ScopedJavaGlobalRef<jobject> java_obj_;
bool use_transparent_background_ = false;
bool requires_alpha_channel_ = false;
raw_ptr<content::WebContents> web_contents_ = nullptr;
std::unique_ptr<content::Compositor> compositor_;
gfx::NativeWindow root_window_;
// Set as the root-layer of the compositor. Contains |web_contents_layer_|.
scoped_refptr<cc::slim::Layer> root_container_layer_;
scoped_refptr<cc::slim::Layer> web_contents_layer_;
base::RepeatingClosure content_height_changed_listener_;
int content_height_ = 0;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_CONTENT_VIEW_RENDER_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/content_view_render_view.h | C++ | unknown | 3,524 |
// 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/files/file_util.h"
#include "base/test/bind.h"
#include "build/build_config.h"
#include "content/public/browser/browser_context.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "weblayer/browser/cookie_manager_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/public/cookie_manager.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
class CookieManagerBrowserTest : public WebLayerBrowserTest {
public:
const std::vector<net::CookieChangeInfo>& WaitForChanges(size_t num) {
if (change_infos_.size() >= num)
return change_infos_;
num_to_wait_for_ = num;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
return change_infos_;
}
void OnCookieChanged(const net::CookieChangeInfo& info) {
change_infos_.push_back(info);
if (run_loop_ && num_to_wait_for_ == change_infos_.size())
run_loop_->Quit();
}
void Reset() { change_infos_.clear(); }
bool SetCookie(const std::string& cookie) {
GURL base_url = embedded_test_server()->base_url();
base::RunLoop run_loop;
bool final_result = false;
GetProfile()->GetCookieManager()->SetCookie(
base_url, cookie,
base::BindLambdaForTesting([&run_loop, &final_result](bool result) {
final_result = result;
run_loop.Quit();
}));
run_loop.Run();
return final_result;
}
base::Time GetCookieDbModifiedTime() {
base::FilePath cookie_path =
GetBrowserContext()->GetPath().Append(FILE_PATH_LITERAL("Cookies"));
base::ScopedAllowBlockingForTesting scoped_allow_blocking;
base::File::Info info;
EXPECT_TRUE(base::GetFileInfo(cookie_path, &info));
return info.last_modified;
}
private:
size_t num_to_wait_for_ = 0;
std::vector<net::CookieChangeInfo> change_infos_;
std::unique_ptr<base::RunLoop> run_loop_;
};
IN_PROC_BROWSER_TEST_F(CookieManagerBrowserTest, CookieChanged) {
EXPECT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page.html"), shell());
GURL base_url = embedded_test_server()->base_url();
base::CallbackListSubscription subscription =
GetProfile()->GetCookieManager()->AddCookieChangedCallback(
base_url, nullptr,
base::BindRepeating(&CookieManagerBrowserTest::OnCookieChanged,
base::Unretained(this)));
ASSERT_TRUE(SetCookie("foo=bar"));
const auto& changes = WaitForChanges(1);
ASSERT_EQ(changes.size(), 1u);
const auto& cookie = changes[0].cookie;
EXPECT_EQ(cookie.Name(), "foo");
EXPECT_EQ(cookie.Value(), "bar");
}
IN_PROC_BROWSER_TEST_F(CookieManagerBrowserTest,
CookieChangedRemoveSubscription) {
EXPECT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page.html"), shell());
GURL base_url = embedded_test_server()->base_url();
std::string cookie1 = "cookie1";
base::CallbackListSubscription subscription1 =
GetProfile()->GetCookieManager()->AddCookieChangedCallback(
base_url, &cookie1,
base::BindRepeating(&CookieManagerBrowserTest::OnCookieChanged,
base::Unretained(this)));
std::string cookie2 = "cookie2";
base::CallbackListSubscription subscription2 =
GetProfile()->GetCookieManager()->AddCookieChangedCallback(
base_url, &cookie2,
base::BindRepeating(&CookieManagerBrowserTest::OnCookieChanged,
base::Unretained(this)));
ASSERT_TRUE(SetCookie("cookie1=something"));
{
const auto& changes = WaitForChanges(1);
ASSERT_EQ(changes.size(), 1u);
EXPECT_EQ(changes[0].cookie.Name(), cookie1);
}
Reset();
subscription1 = {};
// Set cookie1 first and then cookie2. We should only receive a cookie change
// event for cookie2.
ASSERT_TRUE(SetCookie("cookie1=other"));
ASSERT_TRUE(SetCookie("cookie2=something"));
{
const auto& changes = WaitForChanges(1);
ASSERT_EQ(changes.size(), 1u);
EXPECT_EQ(changes[0].cookie.Name(), cookie2);
}
}
IN_PROC_BROWSER_TEST_F(CookieManagerBrowserTest,
DISABLED_FlushCookiesAfterSet) {
EXPECT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page.html"), shell());
base::Time original_modified_time = GetCookieDbModifiedTime();
ASSERT_TRUE(SetCookie("a=b; expires=Fri, 01 Jan 2038 00:00:00 GMT"));
EXPECT_EQ(GetCookieDbModifiedTime(), original_modified_time);
EXPECT_TRUE(static_cast<CookieManagerImpl*>(GetProfile()->GetCookieManager())
->FireFlushTimerForTesting());
EXPECT_GT(GetCookieDbModifiedTime(), original_modified_time);
}
IN_PROC_BROWSER_TEST_F(CookieManagerBrowserTest,
DISABLED_FlushCookiesAfterSetMultiple) {
EXPECT_TRUE(embedded_test_server()->Start());
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page.html"), shell());
base::Time original_modified_time = GetCookieDbModifiedTime();
ASSERT_TRUE(SetCookie("a=b; expires=Fri, 01 Jan 2038 00:00:00 GMT"));
EXPECT_EQ(GetCookieDbModifiedTime(), original_modified_time);
ASSERT_TRUE(SetCookie("c=d; expires=Fri, 01 Jan 2038 00:00:00 GMT"));
EXPECT_EQ(GetCookieDbModifiedTime(), original_modified_time);
CookieManagerImpl* cookie_manager =
static_cast<CookieManagerImpl*>(GetProfile()->GetCookieManager());
EXPECT_TRUE(cookie_manager->FireFlushTimerForTesting());
EXPECT_GT(GetCookieDbModifiedTime(), original_modified_time);
// Flush timer should be gone now.
EXPECT_FALSE(cookie_manager->FireFlushTimerForTesting());
// Try again to make sure it works a second time.
original_modified_time = GetCookieDbModifiedTime();
ASSERT_TRUE(SetCookie("d=f; expires=Fri, 01 Jan 2038 00:00:00 GMT"));
EXPECT_EQ(GetCookieDbModifiedTime(), original_modified_time);
EXPECT_TRUE(cookie_manager->FireFlushTimerForTesting());
EXPECT_GT(GetCookieDbModifiedTime(), original_modified_time);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/cookie_manager_browsertest.cc | C++ | unknown | 6,345 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/cookie_manager_impl.h"
#include "build/build_config.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/storage_partition.h"
#include "net/cookies/cookie_constants.h"
#include "net/cookies/cookie_util.h"
#include "net/cookies/parsed_cookie.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/callback_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "weblayer/browser/java/jni/CookieManagerImpl_jni.h"
#endif
namespace weblayer {
namespace {
constexpr base::TimeDelta kCookieFlushDelay = base::Seconds(1);
void GetCookieComplete(CookieManager::GetCookieCallback callback,
const net::CookieAccessResultList& cookies,
const net::CookieAccessResultList& excluded_cookies) {
net::CookieList cookie_list = net::cookie_util::StripAccessResults(cookies);
std::move(callback).Run(net::CanonicalCookie::BuildCookieLine(cookie_list));
}
void GetResponseCookiesComplete(
CookieManager::GetResponseCookiesCallback callback,
const net::CookieAccessResultList& cookies,
const net::CookieAccessResultList& excluded_cookies) {
net::CookieList cookie_list = net::cookie_util::StripAccessResults(cookies);
std::vector<std::string> response_cookies;
for (const net::CanonicalCookie& cookie : cookie_list) {
net::ParsedCookie parsed("");
parsed.SetName(cookie.Name());
parsed.SetValue(cookie.Value());
parsed.SetPath(cookie.Path());
parsed.SetDomain(cookie.Domain());
if (!cookie.ExpiryDate().is_null())
parsed.SetExpires(base::TimeFormatHTTP(cookie.ExpiryDate()));
parsed.SetIsSecure(cookie.IsSecure());
parsed.SetIsHttpOnly(cookie.IsHttpOnly());
if (cookie.SameSite() != net::CookieSameSite::UNSPECIFIED)
parsed.SetSameSite(net::CookieSameSiteToString(cookie.SameSite()));
parsed.SetPriority(net::CookiePriorityToString(cookie.Priority()));
parsed.SetIsSameParty(cookie.IsSameParty());
parsed.SetIsPartitioned(cookie.IsPartitioned());
response_cookies.push_back(parsed.ToCookieLine());
}
std::move(callback).Run(response_cookies);
}
#if BUILDFLAG(IS_ANDROID)
void OnCookieChangedAndroid(
base::android::ScopedJavaGlobalRef<jobject> callback,
const net::CookieChangeInfo& change) {
JNIEnv* env = base::android::AttachCurrentThread();
Java_CookieManagerImpl_onCookieChange(
env, callback,
base::android::ConvertUTF8ToJavaString(
env, net::CanonicalCookie::BuildCookieLine({change.cookie})),
static_cast<int>(change.cause));
}
void RunGetResponseCookiesCallback(
const base::android::JavaRef<jobject>& callback,
const std::vector<std::string>& cookies) {
JNIEnv* env = base::android::AttachCurrentThread();
base::android::RunObjectCallbackAndroid(
callback, base::android::ToJavaArrayOfStrings(env, cookies));
}
#endif
void OnCookieChanged(CookieManager::CookieChangedCallbackList* callback_list,
const net::CookieChangeInfo& change) {
callback_list->Notify(change);
}
class CookieChangeListenerImpl : public network::mojom::CookieChangeListener {
public:
explicit CookieChangeListenerImpl(
CookieManager::CookieChangedCallback callback)
: callback_(std::move(callback)) {}
// mojom::CookieChangeListener
void OnCookieChange(const net::CookieChangeInfo& change) override {
callback_.Run(change);
}
private:
CookieManager::CookieChangedCallback callback_;
};
} // namespace
CookieManagerImpl::CookieManagerImpl(content::BrowserContext* browser_context)
: browser_context_(browser_context) {}
CookieManagerImpl::~CookieManagerImpl() = default;
void CookieManagerImpl::SetCookie(const GURL& url,
const std::string& value,
SetCookieCallback callback) {
SetCookieInternal(url, value, std::move(callback));
}
void CookieManagerImpl::GetCookie(const GURL& url, GetCookieCallback callback) {
browser_context_->GetDefaultStoragePartition()
->GetCookieManagerForBrowserProcess()
->GetCookieList(url, net::CookieOptions::MakeAllInclusive(),
net::CookiePartitionKeyCollection::Todo(),
base::BindOnce(&GetCookieComplete, std::move(callback)));
}
void CookieManagerImpl::GetResponseCookies(
const GURL& url,
GetResponseCookiesCallback callback) {
browser_context_->GetDefaultStoragePartition()
->GetCookieManagerForBrowserProcess()
->GetCookieList(
url, net::CookieOptions::MakeAllInclusive(),
net::CookiePartitionKeyCollection::Todo(),
base::BindOnce(&GetResponseCookiesComplete, std::move(callback)));
}
base::CallbackListSubscription CookieManagerImpl::AddCookieChangedCallback(
const GURL& url,
const std::string* name,
CookieChangedCallback callback) {
auto callback_list = std::make_unique<CookieChangedCallbackList>();
auto* callback_list_ptr = callback_list.get();
int id = AddCookieChangedCallbackInternal(
url, name,
base::BindRepeating(&OnCookieChanged,
base::Owned(std::move(callback_list))));
callback_list_ptr->set_removal_callback(base::BindRepeating(
&CookieManagerImpl::RemoveCookieChangedCallbackInternal,
weak_factory_.GetWeakPtr(), id));
return callback_list_ptr->Add(std::move(callback));
}
#if BUILDFLAG(IS_ANDROID)
void CookieManagerImpl::SetCookie(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& url,
const base::android::JavaParamRef<jstring>& value,
const base::android::JavaParamRef<jobject>& callback) {
SetCookieInternal(
GURL(ConvertJavaStringToUTF8(url)), ConvertJavaStringToUTF8(value),
base::BindOnce(&base::android::RunBooleanCallbackAndroid,
base::android::ScopedJavaGlobalRef<jobject>(callback)));
}
void CookieManagerImpl::GetCookie(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& url,
const base::android::JavaParamRef<jobject>& callback) {
GetCookie(
GURL(ConvertJavaStringToUTF8(url)),
base::BindOnce(&base::android::RunStringCallbackAndroid,
base::android::ScopedJavaGlobalRef<jobject>(callback)));
}
void CookieManagerImpl::GetResponseCookies(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& url,
const base::android::JavaParamRef<jobject>& callback) {
GetResponseCookies(
GURL(ConvertJavaStringToUTF8(url)),
base::BindOnce(&RunGetResponseCookiesCallback,
base::android::ScopedJavaGlobalRef<jobject>(callback)));
}
int CookieManagerImpl::AddCookieChangedCallback(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& url,
const base::android::JavaParamRef<jstring>& name,
const base::android::JavaParamRef<jobject>& callback) {
std::string name_str;
if (name)
name_str = ConvertJavaStringToUTF8(name);
return AddCookieChangedCallbackInternal(
GURL(ConvertJavaStringToUTF8(url)), name ? &name_str : nullptr,
base::BindRepeating(
&OnCookieChangedAndroid,
base::android::ScopedJavaGlobalRef<jobject>(callback)));
}
void CookieManagerImpl::RemoveCookieChangedCallback(JNIEnv* env, int id) {
RemoveCookieChangedCallbackInternal(id);
}
#endif
bool CookieManagerImpl::FireFlushTimerForTesting() {
if (!flush_timer_)
return false;
flush_run_loop_for_testing_ = std::make_unique<base::RunLoop>();
flush_timer_->FireNow();
flush_run_loop_for_testing_->Run();
flush_run_loop_for_testing_ = nullptr;
return true;
}
void CookieManagerImpl::SetCookieInternal(const GURL& url,
const std::string& value,
SetCookieCallback callback) {
auto cc = net::CanonicalCookie::Create(url, value, base::Time::Now(),
absl::nullopt, absl::nullopt);
if (!cc) {
std::move(callback).Run(false);
return;
}
browser_context_->GetDefaultStoragePartition()
->GetCookieManagerForBrowserProcess()
->SetCanonicalCookie(
*cc, url, net::CookieOptions::MakeAllInclusive(),
base::BindOnce(net::cookie_util::IsCookieAccessResultInclude)
.Then(base::BindOnce(&CookieManagerImpl::OnCookieSet,
weak_factory_.GetWeakPtr(),
std::move(callback))));
}
int CookieManagerImpl::AddCookieChangedCallbackInternal(
const GURL& url,
const std::string* name,
CookieChangedCallback callback) {
mojo::PendingRemote<network::mojom::CookieChangeListener> listener_remote;
auto receiver = listener_remote.InitWithNewPipeAndPassReceiver();
browser_context_->GetDefaultStoragePartition()
->GetCookieManagerForBrowserProcess()
->AddCookieChangeListener(
url, name ? absl::make_optional(*name) : absl::nullopt,
std::move(listener_remote));
auto listener =
std::make_unique<CookieChangeListenerImpl>(std::move(callback));
auto* listener_ptr = listener.get();
return cookie_change_receivers_.Add(listener_ptr, std::move(receiver),
std::move(listener));
}
void CookieManagerImpl::RemoveCookieChangedCallbackInternal(int id) {
cookie_change_receivers_.Remove(id);
}
void CookieManagerImpl::OnCookieSet(SetCookieCallback callback, bool success) {
std::move(callback).Run(success);
if (!flush_timer_) {
flush_timer_ = std::make_unique<base::OneShotTimer>();
flush_timer_->Start(FROM_HERE, kCookieFlushDelay,
base::BindOnce(&CookieManagerImpl::OnFlushTimerFired,
weak_factory_.GetWeakPtr()));
}
}
void CookieManagerImpl::OnFlushTimerFired() {
browser_context_->GetDefaultStoragePartition()
->GetCookieManagerForBrowserProcess()
->FlushCookieStore(flush_run_loop_for_testing_
? flush_run_loop_for_testing_->QuitClosure()
: base::DoNothing());
flush_timer_ = nullptr;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/cookie_manager_impl.cc | C++ | unknown | 10,315 |
// 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_COOKIE_MANAGER_IMPL_H_
#define WEBLAYER_BROWSER_COOKIE_MANAGER_IMPL_H_
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"
#include "weblayer/public/cookie_manager.h"
#if BUILDFLAG(IS_ANDROID)
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#endif
namespace content {
class BrowserContext;
}
namespace weblayer {
class CookieManagerImpl : public CookieManager {
public:
explicit CookieManagerImpl(content::BrowserContext* browser_context);
~CookieManagerImpl() override;
CookieManagerImpl(const CookieManagerImpl&) = delete;
CookieManagerImpl& operator=(const CookieManagerImpl&) = delete;
// CookieManager implementation:
void SetCookie(const GURL& url,
const std::string& value,
SetCookieCallback callback) override;
void GetCookie(const GURL& url, GetCookieCallback callback) override;
void GetResponseCookies(const GURL& url,
GetResponseCookiesCallback callback) override;
base::CallbackListSubscription AddCookieChangedCallback(
const GURL& url,
const std::string* name,
CookieChangedCallback callback) override;
#if BUILDFLAG(IS_ANDROID)
void SetCookie(JNIEnv* env,
const base::android::JavaParamRef<jstring>& url,
const base::android::JavaParamRef<jstring>& value,
const base::android::JavaParamRef<jobject>& callback);
void GetCookie(JNIEnv* env,
const base::android::JavaParamRef<jstring>& url,
const base::android::JavaParamRef<jobject>& callback);
void GetResponseCookies(JNIEnv* env,
const base::android::JavaParamRef<jstring>& url,
const base::android::JavaParamRef<jobject>& callback);
int AddCookieChangedCallback(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& url,
const base::android::JavaParamRef<jstring>& name,
const base::android::JavaParamRef<jobject>& callback);
void RemoveCookieChangedCallback(JNIEnv* env, int id);
#endif
// Fires the cookie flush timer immediately and waits for the flush to
// complete. Returns true if the flush timer was running.
bool FireFlushTimerForTesting();
private:
void SetCookieInternal(const GURL& url,
const std::string& value,
SetCookieCallback callback);
int AddCookieChangedCallbackInternal(const GURL& url,
const std::string* name,
CookieChangedCallback callback);
void RemoveCookieChangedCallbackInternal(int id);
void OnCookieSet(SetCookieCallback callback, bool success);
void OnFlushTimerFired();
raw_ptr<content::BrowserContext> browser_context_;
mojo::ReceiverSet<network::mojom::CookieChangeListener,
std::unique_ptr<network::mojom::CookieChangeListener>>
cookie_change_receivers_;
std::unique_ptr<base::OneShotTimer> flush_timer_;
std::unique_ptr<base::RunLoop> flush_run_loop_for_testing_;
base::WeakPtrFactory<CookieManagerImpl> weak_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_COOKIE_MANAGER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/cookie_manager_impl.h | C++ | unknown | 3,544 |
// 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/cookie_settings_factory.h"
#include "base/no_destructor.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/host_content_settings_map_factory.h"
namespace weblayer {
// static
scoped_refptr<content_settings::CookieSettings>
CookieSettingsFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
return static_cast<content_settings::CookieSettings*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true).get());
}
// static
CookieSettingsFactory* CookieSettingsFactory::GetInstance() {
static base::NoDestructor<CookieSettingsFactory> factory;
return factory.get();
}
CookieSettingsFactory::CookieSettingsFactory()
: RefcountedBrowserContextKeyedServiceFactory(
"CookieSettings",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
CookieSettingsFactory::~CookieSettingsFactory() = default;
void CookieSettingsFactory::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
content_settings::CookieSettings::RegisterProfilePrefs(registry);
}
content::BrowserContext* CookieSettingsFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
scoped_refptr<RefcountedKeyedService>
CookieSettingsFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new content_settings::CookieSettings(
HostContentSettingsMapFactory::GetForBrowserContext(context),
static_cast<BrowserContextImpl*>(context)->pref_service(),
context->IsOffTheRecord());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/cookie_settings_factory.cc | C++ | unknown | 2,130 |
// 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_COOKIE_SETTINGS_FACTORY_H_
#define WEBLAYER_BROWSER_COOKIE_SETTINGS_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/refcounted_browser_context_keyed_service_factory.h"
namespace content_settings {
class CookieSettings;
}
namespace weblayer {
class CookieSettingsFactory
: public RefcountedBrowserContextKeyedServiceFactory {
public:
CookieSettingsFactory(const CookieSettingsFactory&) = delete;
CookieSettingsFactory& operator=(const CookieSettingsFactory&) = delete;
static scoped_refptr<content_settings::CookieSettings> GetForBrowserContext(
content::BrowserContext* browser_context);
static CookieSettingsFactory* GetInstance();
private:
friend class base::NoDestructor<CookieSettingsFactory>;
CookieSettingsFactory();
~CookieSettingsFactory() override;
// BrowserContextKeyedServiceFactory methods:
void RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
scoped_refptr<RefcountedKeyedService> BuildServiceInstanceFor(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_COOKIE_SETTINGS_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/cookie_settings_factory.h | C++ | unknown | 1,449 |
// 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/devtools_manager_delegate_android.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/profile_impl.h"
namespace weblayer {
DevToolsManagerDelegateAndroid::DevToolsManagerDelegateAndroid() = default;
DevToolsManagerDelegateAndroid::~DevToolsManagerDelegateAndroid() = default;
content::BrowserContext*
DevToolsManagerDelegateAndroid::GetDefaultBrowserContext() {
auto profiles = ProfileImpl::GetAllProfiles();
if (profiles.empty())
return nullptr;
// This is called when granting permissions via devtools in browser tests or WPT. We assume that
// there is only a single profile and just pick the first one here. Note that outside of tests
// there might exist multiple profiles for WebLayer and this assumption won't hold.
ProfileImpl* profile = *profiles.begin();
return profile->GetBrowserContext();
}
std::string DevToolsManagerDelegateAndroid::GetDiscoveryPageHTML() {
const char html[] =
"<html>"
"<head><title>WebLayer remote debugging</title></head>"
"<body>Please use <a href=\'chrome://inspect\'>chrome://inspect</a>"
"</body>"
"</html>";
return html;
}
bool DevToolsManagerDelegateAndroid::IsBrowserTargetDiscoverable() {
return true;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/devtools_manager_delegate_android.cc | C++ | unknown | 1,435 |
// 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_DEVTOOLS_MANAGER_DELEGATE_ANDROID_H_
#define WEBLAYER_BROWSER_DEVTOOLS_MANAGER_DELEGATE_ANDROID_H_
#include "content/public/browser/devtools_manager_delegate.h"
namespace weblayer {
class DevToolsManagerDelegateAndroid : public content::DevToolsManagerDelegate {
public:
DevToolsManagerDelegateAndroid();
DevToolsManagerDelegateAndroid(const DevToolsManagerDelegateAndroid&) =
delete;
DevToolsManagerDelegateAndroid& operator=(
const DevToolsManagerDelegateAndroid&) = delete;
~DevToolsManagerDelegateAndroid() override;
// content::DevToolsManagerDelegate implementation.
content::BrowserContext* GetDefaultBrowserContext() override;
std::string GetDiscoveryPageHTML() override;
bool IsBrowserTargetDiscoverable() override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_DEVTOOLS_MANAGER_DELEGATE_ANDROID_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/devtools_manager_delegate_android.h | C++ | unknown | 1,024 |
// 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/devtools_server_android.h"
#include "base/command_line.h"
#include "base/strings/stringprintf.h"
#include "content/public/browser/android/devtools_auth.h"
#include "content/public/browser/devtools_manager_delegate.h"
#include "content/public/browser/devtools_socket_factory.h"
#include "content/public/common/content_switches.h"
#include "net/base/net_errors.h"
#include "net/socket/unix_domain_server_socket_posix.h"
namespace weblayer {
namespace {
bool g_remote_debugging_enabled = false;
const int kBackLog = 10;
const char kSocketNameFormat[] = "weblayer_devtools_remote_%d";
const char kTetheringSocketName[] = "weblayer_devtools_tethering_%d_%d";
class UnixDomainServerSocketFactory : public content::DevToolsSocketFactory {
public:
explicit UnixDomainServerSocketFactory(const std::string& socket_name)
: socket_name_(socket_name) {}
UnixDomainServerSocketFactory(const UnixDomainServerSocketFactory&) = delete;
UnixDomainServerSocketFactory& operator=(
const UnixDomainServerSocketFactory&) = delete;
private:
// content::DevToolsAgentHost::ServerSocketFactory.
std::unique_ptr<net::ServerSocket> CreateForHttpServer() override {
auto socket = std::make_unique<net::UnixDomainServerSocket>(
base::BindRepeating(&content::CanUserConnectToDevTools),
true /* use_abstract_namespace */);
if (socket->BindAndListen(socket_name_, kBackLog) != net::OK)
return nullptr;
return std::move(socket);
}
std::unique_ptr<net::ServerSocket> CreateForTethering(
std::string* name) override {
*name = base::StringPrintf(kTetheringSocketName, getpid(),
++last_tethering_socket_);
auto socket = std::make_unique<net::UnixDomainServerSocket>(
base::BindRepeating(&content::CanUserConnectToDevTools),
true /* use_abstract_namespace */);
if (socket->BindAndListen(*name, kBackLog) != net::OK)
return nullptr;
return std::move(socket);
}
std::string socket_name_;
int last_tethering_socket_ = 0;
};
} // namespace
// static
void DevToolsServerAndroid::SetRemoteDebuggingEnabled(bool enabled) {
if (g_remote_debugging_enabled == enabled)
return;
g_remote_debugging_enabled = enabled;
if (enabled) {
auto factory = std::make_unique<UnixDomainServerSocketFactory>(
base::StringPrintf(kSocketNameFormat, getpid()));
content::DevToolsAgentHost::StartRemoteDebuggingServer(
std::move(factory), base::FilePath(), base::FilePath());
} else {
content::DevToolsAgentHost::StopRemoteDebuggingServer();
}
}
// static
bool DevToolsServerAndroid::GetRemoteDebuggingEnabled() {
return g_remote_debugging_enabled;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/devtools_server_android.cc | C++ | unknown | 2,885 |
// 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_DEVTOOLS_SERVER_ANDROID_H_
#define WEBLAYER_BROWSER_DEVTOOLS_SERVER_ANDROID_H_
namespace weblayer {
class DevToolsServerAndroid {
public:
static void SetRemoteDebuggingEnabled(bool enabled);
static bool GetRemoteDebuggingEnabled();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_DEVTOOLS_SERVER_ANDROID_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/devtools_server_android.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/test/weblayer_browser_test.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/slow_download_http_response.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/download_manager_delegate_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/download.h"
#include "weblayer/public/download_delegate.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/test_navigation_observer.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
namespace {
class DownloadBrowserTest : public WebLayerBrowserTest,
public DownloadDelegate {
public:
DownloadBrowserTest() = default;
~DownloadBrowserTest() override = default;
void SetUpOnMainThread() override {
embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
&content::SlowDownloadHttpResponse::HandleSlowDownloadRequest));
ASSERT_TRUE(embedded_test_server()->Start());
allow_run_loop_ = std::make_unique<base::RunLoop>();
started_run_loop_ = std::make_unique<base::RunLoop>();
intercept_run_loop_ = std::make_unique<base::RunLoop>();
completed_run_loop_ = std::make_unique<base::RunLoop>();
failed_run_loop_ = std::make_unique<base::RunLoop>();
Tab* tab = shell()->tab();
TabImpl* tab_impl = static_cast<TabImpl*>(tab);
tab_impl->profile()->SetDownloadDelegate(this);
auto* browser_context = tab_impl->web_contents()->GetBrowserContext();
auto* download_manager_delegate =
browser_context->GetDownloadManager()->GetDelegate();
static_cast<DownloadManagerDelegateImpl*>(download_manager_delegate)
->set_download_dropped_closure_for_testing(base::BindRepeating(
&DownloadBrowserTest::DownloadDropped, base::Unretained(this)));
}
void WaitForAllow() { allow_run_loop_->Run(); }
void WaitForIntercept() { intercept_run_loop_->Run(); }
void WaitForStarted() { started_run_loop_->Run(); }
void WaitForCompleted() { completed_run_loop_->Run(); }
void WaitForFailed() { failed_run_loop_->Run(); }
void set_intercept() { intercept_ = true; }
void set_disallow() { allow_ = false; }
void set_started_callback(
base::OnceCallback<void(Download* download)> callback) {
started_callback_ = std::move(callback);
}
void set_failed_callback(
base::OnceCallback<void(Download* download)> callback) {
failed_callback_ = std::move(callback);
}
bool started() { return started_; }
base::FilePath download_location() { return download_location_; }
int64_t total_bytes() { return total_bytes_; }
DownloadError download_state() { return download_state_; }
std::string mime_type() { return mime_type_; }
int completed_count() { return completed_count_; }
int failed_count() { return failed_count_; }
int download_dropped_count() { return download_dropped_count_; }
private:
// DownloadDelegate implementation:
void AllowDownload(Tab* tab,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
AllowDownloadCallback callback) override {
std::move(callback).Run(allow_);
allow_run_loop_->Quit();
}
bool InterceptDownload(const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
int64_t content_length) override {
intercept_run_loop_->Quit();
return intercept_;
}
void DownloadStarted(Download* download) override {
started_ = true;
started_run_loop_->Quit();
CHECK_EQ(download->GetState(), DownloadState::kInProgress);
if (started_callback_)
std::move(started_callback_).Run(download);
}
void DownloadCompleted(Download* download) override {
completed_count_++;
download_location_ = download->GetLocation();
total_bytes_ = download->GetTotalBytes();
download_state_ = download->GetError();
mime_type_ = download->GetMimeType();
CHECK_EQ(download->GetReceivedBytes(), total_bytes_);
CHECK_EQ(download->GetState(), DownloadState::kComplete);
completed_run_loop_->Quit();
}
void DownloadFailed(Download* download) override {
failed_count_++;
download_state_ = download->GetError();
failed_run_loop_->Quit();
if (failed_callback_)
std::move(failed_callback_).Run(download);
}
void DownloadDropped() { download_dropped_count_++; }
bool intercept_ = false;
bool allow_ = true;
bool started_ = false;
base::OnceCallback<void(Download* download)> started_callback_;
base::OnceCallback<void(Download* download)> failed_callback_;
base::FilePath download_location_;
int64_t total_bytes_ = 0;
DownloadError download_state_ = DownloadError::kNoError;
std::string mime_type_;
int completed_count_ = 0;
int failed_count_ = 0;
int download_dropped_count_ = 0;
std::unique_ptr<base::RunLoop> allow_run_loop_;
std::unique_ptr<base::RunLoop> intercept_run_loop_;
std::unique_ptr<base::RunLoop> started_run_loop_;
std::unique_ptr<base::RunLoop> completed_run_loop_;
std::unique_ptr<base::RunLoop> failed_run_loop_;
};
} // namespace
// Ensures that if the delegate disallows the downloads then WebLayer
// doesn't download it.
IN_PROC_BROWSER_TEST_F(DownloadBrowserTest, DisallowNoDownload) {
set_disallow();
GURL url(embedded_test_server()->GetURL("/content-disposition.html"));
// Downloads always count as failed navigations.
TestNavigationObserver observer(
url, TestNavigationObserver::NavigationEvent::kFailure, shell());
shell()->tab()->GetNavigationController()->Navigate(url);
observer.Wait();
WaitForAllow();
EXPECT_FALSE(started());
EXPECT_EQ(completed_count(), 0);
EXPECT_EQ(failed_count(), 0);
EXPECT_EQ(download_dropped_count(), 1);
}
// Ensures that if the delegate chooses to intercept downloads then WebLayer
// doesn't download it.
IN_PROC_BROWSER_TEST_F(DownloadBrowserTest, InterceptNoDownload) {
set_intercept();
GURL url(embedded_test_server()->GetURL("/content-disposition.html"));
shell()->tab()->GetNavigationController()->Navigate(url);
WaitForIntercept();
EXPECT_FALSE(started());
EXPECT_EQ(completed_count(), 0);
EXPECT_EQ(failed_count(), 0);
EXPECT_EQ(download_dropped_count(), 1);
}
IN_PROC_BROWSER_TEST_F(DownloadBrowserTest, Basic) {
GURL url(embedded_test_server()->GetURL("/content-disposition.html"));
shell()->tab()->GetNavigationController()->Navigate(url);
WaitForCompleted();
EXPECT_TRUE(started());
EXPECT_EQ(completed_count(), 1);
EXPECT_EQ(failed_count(), 0);
EXPECT_EQ(download_dropped_count(), 0);
EXPECT_EQ(download_state(), DownloadError::kNoError);
EXPECT_EQ(mime_type(), "text/html");
// Check that the size on disk matches what's expected.
{
base::ScopedAllowBlockingForTesting allow_blocking;
int64_t downloaded_file_size, original_file_size;
EXPECT_TRUE(base::GetFileSize(download_location(), &downloaded_file_size));
base::FilePath test_data_dir;
CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &test_data_dir));
EXPECT_TRUE(base::GetFileSize(
test_data_dir.Append(base::FilePath(
FILE_PATH_LITERAL("weblayer/test/data/content-disposition.html"))),
&original_file_size));
EXPECT_EQ(downloaded_file_size, total_bytes());
}
// Ensure browser tests don't write to the default machine download directory
// to avoid filing it up.
EXPECT_NE(BrowserContextImpl::GetDefaultDownloadDirectory(),
download_location().DirName());
}
IN_PROC_BROWSER_TEST_F(DownloadBrowserTest, OverrideDownloadDirectory) {
base::ScopedAllowBlockingForTesting allow_blocking;
base::ScopedTempDir download_dir;
ASSERT_TRUE(download_dir.CreateUniqueTempDir());
TabImpl* tab_impl = static_cast<TabImpl*>(shell()->tab());
auto* browser_context = tab_impl->web_contents()->GetBrowserContext();
auto* browser_context_impl =
static_cast<BrowserContextImpl*>(browser_context);
browser_context_impl->profile_impl()->SetDownloadDirectory(
download_dir.GetPath());
GURL url(embedded_test_server()->GetURL("/content-disposition.html"));
shell()->tab()->GetNavigationController()->Navigate(url);
WaitForCompleted();
EXPECT_EQ(completed_count(), 1);
EXPECT_EQ(failed_count(), 0);
EXPECT_EQ(download_dir.GetPath(), download_location().DirName());
}
IN_PROC_BROWSER_TEST_F(DownloadBrowserTest, Cancel) {
set_started_callback(base::BindLambdaForTesting([&](Download* download) {
download->Cancel();
// Also allow the download to complete.
GURL url = embedded_test_server()->GetURL(
content::SlowDownloadHttpResponse::kFinishSlowResponseUrl);
shell()->tab()->GetNavigationController()->Navigate(url);
}));
set_failed_callback(base::BindLambdaForTesting([](Download* download) {
CHECK_EQ(download->GetState(), DownloadState::kCancelled);
}));
// Create a request that doesn't complete right away to avoid flakiness.
GURL url(embedded_test_server()->GetURL(
content::SlowDownloadHttpResponse::kKnownSizeUrl));
shell()->tab()->GetNavigationController()->Navigate(url);
WaitForFailed();
EXPECT_EQ(completed_count(), 0);
EXPECT_EQ(failed_count(), 1);
EXPECT_EQ(download_dropped_count(), 0);
EXPECT_EQ(download_state(), DownloadError::kCancelled);
}
IN_PROC_BROWSER_TEST_F(DownloadBrowserTest, PauseResume) {
// Add an initial navigation to avoid the tab being deleted if the first
// navigation is a download, since we use the tab for convenience in the
// lambda.
OneShotNavigationObserver observer(shell());
shell()->tab()->GetNavigationController()->Navigate(GURL("about:blank"));
observer.WaitForNavigation();
set_started_callback(base::BindLambdaForTesting([&](Download* download) {
download->Pause();
GURL url = embedded_test_server()->GetURL(
content::SlowDownloadHttpResponse::kFinishSlowResponseUrl);
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(
[](Download* download, Shell* shell, const GURL& url) {
CHECK_EQ(download->GetState(), DownloadState::kPaused);
download->Resume();
// Also allow the download to complete.
shell->tab()->GetNavigationController()->Navigate(url);
},
download, shell(), url));
}));
// Create a request that doesn't complete right away to avoid flakiness.
GURL url(embedded_test_server()->GetURL(
content::SlowDownloadHttpResponse::kKnownSizeUrl));
shell()->tab()->GetNavigationController()->Navigate(url);
WaitForCompleted();
EXPECT_EQ(completed_count(), 1);
EXPECT_EQ(failed_count(), 0);
EXPECT_EQ(download_dropped_count(), 0);
}
IN_PROC_BROWSER_TEST_F(DownloadBrowserTest, NetworkError) {
set_failed_callback(base::BindLambdaForTesting([](Download* download) {
CHECK_EQ(download->GetState(), DownloadState::kFailed);
}));
// Create a request that doesn't complete right away.
GURL url(embedded_test_server()->GetURL(
content::SlowDownloadHttpResponse::kKnownSizeUrl));
shell()->tab()->GetNavigationController()->Navigate(url);
WaitForStarted();
EXPECT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
WaitForFailed();
EXPECT_EQ(completed_count(), 0);
EXPECT_EQ(failed_count(), 1);
EXPECT_EQ(download_dropped_count(), 0);
EXPECT_EQ(download_state(), DownloadError::kConnectivityError);
}
IN_PROC_BROWSER_TEST_F(DownloadBrowserTest, PendingOnExist) {
// Create a request that doesn't complete right away.
GURL url(embedded_test_server()->GetURL(
content::SlowDownloadHttpResponse::kKnownSizeUrl));
shell()->tab()->GetNavigationController()->Navigate(url);
WaitForStarted();
// If this test crashes later then there'd be a regression.
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/download_browsertest.cc | C++ | unknown | 12,747 |
// 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/download_callback_proxy.h"
#include "base/android/jni_string.h"
#include "base/trace_event/trace_event.h"
#include "url/android/gurl_android.h"
#include "url/gurl.h"
#include "weblayer/browser/download_impl.h"
#include "weblayer/browser/java/jni/DownloadCallbackProxy_jni.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
using base::android::AttachCurrentThread;
using base::android::ConvertUTF8ToJavaString;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
DownloadCallbackProxy::DownloadCallbackProxy(JNIEnv* env,
jobject obj,
Profile* profile)
: profile_(profile), java_delegate_(env, obj) {
profile_->SetDownloadDelegate(this);
}
DownloadCallbackProxy::~DownloadCallbackProxy() {
profile_->SetDownloadDelegate(nullptr);
}
bool DownloadCallbackProxy::InterceptDownload(
const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
int64_t content_length) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jstring> jstring_url(
ConvertUTF8ToJavaString(env, url.spec()));
ScopedJavaLocalRef<jstring> jstring_user_agent(
ConvertUTF8ToJavaString(env, user_agent));
ScopedJavaLocalRef<jstring> jstring_content_disposition(
ConvertUTF8ToJavaString(env, content_disposition));
ScopedJavaLocalRef<jstring> jstring_mime_type(
ConvertUTF8ToJavaString(env, mime_type));
TRACE_EVENT0("weblayer", "Java_DownloadCallbackProxy_interceptDownload");
return Java_DownloadCallbackProxy_interceptDownload(
env, java_delegate_, jstring_url, jstring_user_agent,
jstring_content_disposition, jstring_mime_type, content_length);
}
void DownloadCallbackProxy::AllowDownload(
Tab* tab,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
AllowDownloadCallback callback) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jstring> jstring_url(
ConvertUTF8ToJavaString(env, url.spec()));
ScopedJavaLocalRef<jstring> jstring_method(
ConvertUTF8ToJavaString(env, request_method));
ScopedJavaLocalRef<jstring> jstring_request_initator;
if (request_initiator)
jstring_request_initator =
ConvertUTF8ToJavaString(env, request_initiator->Serialize());
// Make copy on the heap so we can pass the pointer through JNI. This will be
// deleted when it's run.
intptr_t callback_id = reinterpret_cast<intptr_t>(
new AllowDownloadCallback(std::move(callback)));
Java_DownloadCallbackProxy_allowDownload(
env, java_delegate_, static_cast<TabImpl*>(tab)->GetJavaTab(),
jstring_url, jstring_method, jstring_request_initator, callback_id);
}
void DownloadCallbackProxy::DownloadStarted(Download* download) {
DownloadImpl* download_impl = static_cast<DownloadImpl*>(download);
JNIEnv* env = AttachCurrentThread();
Java_DownloadCallbackProxy_createDownload(
env, java_delegate_, reinterpret_cast<jlong>(download_impl),
download_impl->GetNotificationId(), download_impl->IsTransient(),
url::GURLAndroid::FromNativeGURL(env, download_impl->GetSourceUrl()));
Java_DownloadCallbackProxy_downloadStarted(env, java_delegate_,
download_impl->java_download());
}
void DownloadCallbackProxy::DownloadProgressChanged(Download* download) {
DownloadImpl* download_impl = static_cast<DownloadImpl*>(download);
Java_DownloadCallbackProxy_downloadProgressChanged(
AttachCurrentThread(), java_delegate_, download_impl->java_download());
}
void DownloadCallbackProxy::DownloadCompleted(Download* download) {
DownloadImpl* download_impl = static_cast<DownloadImpl*>(download);
Java_DownloadCallbackProxy_downloadCompleted(
AttachCurrentThread(), java_delegate_, download_impl->java_download());
}
void DownloadCallbackProxy::DownloadFailed(Download* download) {
DownloadImpl* download_impl = static_cast<DownloadImpl*>(download);
Java_DownloadCallbackProxy_downloadFailed(
AttachCurrentThread(), java_delegate_, download_impl->java_download());
}
static jlong JNI_DownloadCallbackProxy_CreateDownloadCallbackProxy(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& proxy,
jlong profile) {
return reinterpret_cast<jlong>(new DownloadCallbackProxy(
env, proxy, reinterpret_cast<ProfileImpl*>(profile)));
}
static void JNI_DownloadCallbackProxy_DeleteDownloadCallbackProxy(JNIEnv* env,
jlong proxy) {
delete reinterpret_cast<DownloadCallbackProxy*>(proxy);
}
static void JNI_DownloadCallbackProxy_AllowDownload(JNIEnv* env,
jlong callback_id,
jboolean allow) {
std::unique_ptr<AllowDownloadCallback> cb(
reinterpret_cast<AllowDownloadCallback*>(callback_id));
std::move(*cb).Run(allow);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/download_callback_proxy.cc | C++ | unknown | 5,261 |
// 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_DOWNLOAD_CALLBACK_PROXY_H_
#define WEBLAYER_BROWSER_DOWNLOAD_CALLBACK_PROXY_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "weblayer/public/download_delegate.h"
namespace weblayer {
class Profile;
// Forwards DownloadDelegate calls to the java-side DownloadCallbackProxy.
class DownloadCallbackProxy : public DownloadDelegate {
public:
DownloadCallbackProxy(JNIEnv* env, jobject obj, Profile* profile);
DownloadCallbackProxy(const DownloadCallbackProxy&) = delete;
DownloadCallbackProxy& operator=(const DownloadCallbackProxy&) = delete;
~DownloadCallbackProxy() override;
// DownloadDelegate:
bool InterceptDownload(const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
int64_t content_length) override;
void AllowDownload(Tab* tab,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
AllowDownloadCallback callback) override;
void DownloadStarted(Download* download) override;
void DownloadProgressChanged(Download* download) override;
void DownloadCompleted(Download* download) override;
void DownloadFailed(Download* download) override;
private:
raw_ptr<Profile> profile_;
base::android::ScopedJavaGlobalRef<jobject> java_delegate_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_DOWNLOAD_CALLBACK_PROXY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/download_callback_proxy.h | C++ | unknown | 1,818 |
// 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/download_impl.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "build/build_config.h"
#include "components/download/public/common/download_item.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/jni_string.h"
#include "ui/gfx/android/java_bitmap.h"
#include "weblayer/browser/java/jni/DownloadImpl_jni.h"
#endif
namespace weblayer {
DownloadImpl::~DownloadImpl() {
#if BUILDFLAG(IS_ANDROID)
if (java_download_) {
Java_DownloadImpl_onNativeDestroyed(base::android::AttachCurrentThread(),
java_download_);
}
#endif
}
#if BUILDFLAG(IS_ANDROID)
void DownloadImpl::SetJavaDownload(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& java_download) {
java_download_.Reset(env, java_download);
}
base::android::ScopedJavaLocalRef<jstring> DownloadImpl::GetLocationImpl(
JNIEnv* env) {
return base::android::ScopedJavaLocalRef<jstring>(
base::android::ConvertUTF8ToJavaString(env, GetLocation().value()));
}
base::android::ScopedJavaLocalRef<jstring>
DownloadImpl::GetFileNameToReportToUserImpl(JNIEnv* env) {
return base::android::ScopedJavaLocalRef<jstring>(
base::android::ConvertUTF16ToJavaString(env,
GetFileNameToReportToUser()));
}
base::android::ScopedJavaLocalRef<jstring> DownloadImpl::GetMimeTypeImpl(
JNIEnv* env) {
return base::android::ScopedJavaLocalRef<jstring>(
base::android::ConvertUTF8ToJavaString(env, GetMimeType()));
}
base::android::ScopedJavaLocalRef<jobject> DownloadImpl::GetLargeIconImpl(
JNIEnv* env) {
base::android::ScopedJavaLocalRef<jobject> j_icon;
const SkBitmap* icon = GetLargeIcon();
if (icon && !icon->drawsNothing())
j_icon = gfx::ConvertToJavaBitmap(*icon);
return j_icon;
}
#endif
DownloadImpl::DownloadImpl() = default;
bool DownloadImpl::HasBeenAddedToUi() {
#if BUILDFLAG(IS_ANDROID)
return static_cast<bool>(java_download_);
#else
// Since there is no UI outside of Android, we'll assume true.
return true;
#endif
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/download_impl.cc | C++ | unknown | 2,294 |
// 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_DOWNLOAD_IMPL_H_
#define WEBLAYER_BROWSER_DOWNLOAD_IMPL_H_
#include "base/memory/weak_ptr.h"
#include "base/supports_user_data.h"
#include "build/build_config.h"
#include "url/gurl.h"
#include "weblayer/public/download.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/scoped_java_ref.h"
#endif
class SkBitmap;
namespace weblayer {
// Base class for downloads that should be represented in the UI.
class DownloadImpl : public Download, public base::SupportsUserData::Data {
public:
~DownloadImpl() override;
DownloadImpl(const DownloadImpl&) = delete;
DownloadImpl& operator=(const DownloadImpl&) = delete;
#if BUILDFLAG(IS_ANDROID)
void SetJavaDownload(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& java_download);
int GetStateImpl(JNIEnv* env) { return static_cast<int>(GetState()); }
jlong GetTotalBytesImpl(JNIEnv* env) { return GetTotalBytes(); }
jlong GetReceivedBytesImpl(JNIEnv* env) { return GetReceivedBytes(); }
void PauseImpl(JNIEnv* env) { Pause(); }
void ResumeImpl(JNIEnv* env) { Resume(); }
void CancelImpl(JNIEnv* env) { Cancel(); }
void OnFinishedImpl(JNIEnv* env, jboolean activated) {
OnFinished(activated);
}
base::android::ScopedJavaLocalRef<jstring> GetLocationImpl(JNIEnv* env);
base::android::ScopedJavaLocalRef<jstring> GetFileNameToReportToUserImpl(
JNIEnv* env);
base::android::ScopedJavaLocalRef<jstring> GetMimeTypeImpl(JNIEnv* env);
int GetErrorImpl(JNIEnv* env) { return static_cast<int>(GetError()); }
base::android::ScopedJavaLocalRef<jobject> GetLargeIconImpl(JNIEnv* env);
base::android::ScopedJavaGlobalRef<jobject> java_download() {
return java_download_;
}
#endif
// Returns an ID suitable for use as an Android notification ID. This must be
// unique across all DownloadImpls.
virtual int GetNotificationId() = 0;
// A transient download is not persisted to disk, which affects its UI
// treatment.
virtual bool IsTransient() = 0;
// Returns the originating URL for this download.
virtual GURL GetSourceUrl() = 0;
// Gets the icon to display. If the return value is null or draws nothing, no
// icon will be displayed.
virtual const SkBitmap* GetLargeIcon() = 0;
// Called when the UI is gone. |activated| is true if the UI was activated, or
// false if it was simply dismissed.
virtual void OnFinished(bool activated) = 0;
// Returns whether this download has been added to the UI via
// DownloadDelegate::OnDownloadStarted.
bool HasBeenAddedToUi();
protected:
DownloadImpl();
private:
#if BUILDFLAG(IS_ANDROID)
base::android::ScopedJavaGlobalRef<jobject> java_download_;
#endif
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_DOWNLOAD_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/download_impl.h | C++ | unknown | 2,898 |
// 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/download_manager_delegate_impl.h"
#include "base/files/file_util.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "components/download/public/common/download_item.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager.h"
#include "net/base/filename_util.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/browser_process.h"
#include "weblayer/browser/download_manager_delegate_impl.h"
#include "weblayer/browser/persistent_download.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/download_delegate.h"
namespace weblayer {
namespace {
void GenerateFilename(
const GURL& url,
const std::string& content_disposition,
const std::string& suggested_filename,
const std::string& mime_type,
const base::FilePath& suggested_directory,
base::OnceCallback<void(const base::FilePath&)> callback) {
base::FilePath generated_name =
net::GenerateFileName(url, content_disposition, std::string(),
suggested_filename, mime_type, "download");
if (!base::PathExists(suggested_directory))
base::CreateDirectory(suggested_directory);
base::FilePath suggested_path(suggested_directory.Append(generated_name));
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), suggested_path));
}
} // namespace
const char kDownloadNextIDPref[] = "weblayer_download_next_id";
DownloadManagerDelegateImpl::DownloadManagerDelegateImpl(
content::DownloadManager* download_manager)
: download_manager_(download_manager) {
download_manager_->AddObserver(this);
// WebLayer doesn't use a history DB as the in-progress database maintained by
// the download component is enough. However the download code still depends
// this notification. TODO(jam): update download code to handle this.
download_manager_->PostInitialization(
content::DownloadManager::DOWNLOAD_INITIALIZATION_DEPENDENCY_HISTORY_DB);
}
DownloadManagerDelegateImpl::~DownloadManagerDelegateImpl() {
download_manager_->RemoveObserver(this);
// Match the AddObserver calls added in OnDownloadCreated to avoid UaF.
download::SimpleDownloadManager::DownloadVector downloads;
download_manager_->GetAllDownloads(&downloads);
for (auto* download : downloads)
download->RemoveObserver(this);
}
void DownloadManagerDelegateImpl::GetNextId(
content::DownloadIdCallback callback) {
// Need to return a unique id, even across crashes, to avoid notification
// intents with different data (e.g. notification GUID) getting dup'd. This is
// also persisted in the on-disk download database to support resumption.
auto* local_state = BrowserProcess::GetInstance()->GetLocalState();
std::move(callback).Run(local_state->GetInteger(kDownloadNextIDPref));
}
bool DownloadManagerDelegateImpl::DetermineDownloadTarget(
download::DownloadItem* item,
content::DownloadTargetCallback* callback) {
if (!item->GetForcedFilePath().empty()) {
std::move(*callback).Run(
item->GetForcedFilePath(),
download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DownloadItem::InsecureDownloadStatus::UNKNOWN,
item->GetForcedFilePath(), base::FilePath(),
std::string() /*mime_type*/, download::DOWNLOAD_INTERRUPT_REASON_NONE);
return true;
}
auto filename_determined_callback = base::BindOnce(
&DownloadManagerDelegateImpl::OnDownloadPathGenerated,
weak_ptr_factory_.GetWeakPtr(), item->GetId(), std::move(*callback));
auto* browser_context = content::DownloadItemUtils::GetBrowserContext(item);
base::FilePath default_download_path;
GetSaveDir(browser_context, nullptr, &default_download_path);
base::ThreadPool::PostTask(
FROM_HERE,
{base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN,
base::TaskPriority::USER_VISIBLE},
base::BindOnce(
GenerateFilename, item->GetURL(), item->GetContentDisposition(),
item->GetSuggestedFilename(), item->GetMimeType(),
default_download_path, std::move(filename_determined_callback)));
return true;
}
bool DownloadManagerDelegateImpl::InterceptDownloadIfApplicable(
const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
const std::string& request_origin,
int64_t content_length,
bool is_transient,
content::WebContents* web_contents) {
// Don't intercept transient downloads (such as Background Fetches).
if (is_transient)
return false;
// If there's no DownloadDelegate, the download is simply dropped.
auto* delegate = GetDelegate(web_contents);
if (!delegate)
return true;
return delegate->InterceptDownload(url, user_agent, content_disposition,
mime_type, content_length);
}
void DownloadManagerDelegateImpl::GetSaveDir(
content::BrowserContext* browser_context,
base::FilePath* website_save_dir,
base::FilePath* download_save_dir) {
auto* browser_context_impl =
static_cast<BrowserContextImpl*>(browser_context);
auto* profile = browser_context_impl->profile_impl();
if (!profile->download_directory().empty())
*download_save_dir = profile->download_directory();
}
void DownloadManagerDelegateImpl::CheckDownloadAllowed(
const content::WebContents::Getter& web_contents_getter,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
bool from_download_cross_origin_redirect,
bool content_initiated,
content::CheckDownloadAllowedCallback check_download_allowed_cb) {
auto* web_contents = web_contents_getter.Run();
// If there's no DownloadDelegate, the download is simply dropped.
auto* delegate = GetDelegate(web_contents);
auto* tab = TabImpl::FromWebContents(web_contents);
if (!delegate || !tab) {
std::move(check_download_allowed_cb).Run(false);
return;
}
delegate->AllowDownload(tab, url, request_method, request_initiator,
std::move(check_download_allowed_cb));
}
void DownloadManagerDelegateImpl::OnDownloadCreated(
content::DownloadManager* manager,
download::DownloadItem* item) {
auto* local_state = BrowserProcess::GetInstance()->GetLocalState();
int next_id = local_state->GetInteger(kDownloadNextIDPref);
if (item->GetId() >= static_cast<uint32_t>(next_id)) {
next_id = item->GetId();
// Reset the counter when it gets close to max value of unsigned 32 bit
// integer since that's what the download system persists.
if (++next_id == (std::numeric_limits<uint32_t>::max() / 2) - 1)
next_id = 0;
local_state->SetInteger(kDownloadNextIDPref, next_id);
}
if (item->IsTransient())
return;
// As per the documentation in DownloadItem, transient items should not
// be shown in the UI. (Note that they may be surface by other means,
// such as through the BackgroundFetch system.)
item->AddObserver(this);
// Create a PersistentDownload which will be owned by |item|.
PersistentDownload::Create(item);
if (item->GetLastReason() == download::DOWNLOAD_INTERRUPT_REASON_CRASH &&
item->CanResume() &&
// Don't automatically resume downloads which were previously paused.
!item->IsPaused()) {
PersistentDownload::Get(item)->Resume();
}
auto* delegate = GetDelegate(item);
if (delegate)
delegate->DownloadStarted(PersistentDownload::Get(item));
}
void DownloadManagerDelegateImpl::OnDownloadDropped(
content::DownloadManager* manager) {
if (download_dropped_callback_)
download_dropped_callback_.Run();
}
void DownloadManagerDelegateImpl::OnManagerInitialized() {
auto* browser_context_impl =
static_cast<BrowserContextImpl*>(download_manager_->GetBrowserContext());
auto* profile = browser_context_impl->profile_impl();
profile->DownloadsInitialized();
}
void DownloadManagerDelegateImpl::OnDownloadUpdated(
download::DownloadItem* item) {
// If this is the first navigation in a tab it should be closed. Wait until
// the target path is determined or the download is canceled to check.
if (!item->GetTargetFilePath().empty() ||
item->GetState() == download::DownloadItem::CANCELLED) {
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
if (web_contents && web_contents->GetController().IsInitialNavigation())
web_contents->Close();
}
auto* delegate = GetDelegate(item);
if (item->GetState() == download::DownloadItem::COMPLETE ||
item->GetState() == download::DownloadItem::CANCELLED ||
item->GetState() == download::DownloadItem::INTERRUPTED) {
// Stop observing now to ensure we only send one complete/fail notification.
item->RemoveObserver(this);
if (item->GetState() == download::DownloadItem::COMPLETE)
delegate->DownloadCompleted(PersistentDownload::Get(item));
else
delegate->DownloadFailed(PersistentDownload::Get(item));
// Needs to happen asynchronously to avoid nested observer calls.
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&DownloadManagerDelegateImpl::RemoveItem,
weak_ptr_factory_.GetWeakPtr(), item->GetGuid()));
return;
}
if (delegate)
delegate->DownloadProgressChanged(PersistentDownload::Get(item));
}
void DownloadManagerDelegateImpl::OnDownloadPathGenerated(
uint32_t download_id,
content::DownloadTargetCallback callback,
const base::FilePath& suggested_path) {
std::move(callback).Run(
suggested_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DownloadItem::InsecureDownloadStatus::UNKNOWN,
suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")),
base::FilePath(), std::string() /*mime_type*/,
download::DOWNLOAD_INTERRUPT_REASON_NONE);
}
void DownloadManagerDelegateImpl::RemoveItem(const std::string& guid) {
auto* item = download_manager_->GetDownloadByGuid(guid);
if (item)
item->Remove();
}
DownloadDelegate* DownloadManagerDelegateImpl::GetDelegate(
content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
return GetDelegate(web_contents->GetBrowserContext());
}
DownloadDelegate* DownloadManagerDelegateImpl::GetDelegate(
content::BrowserContext* browser_context) {
auto* profile = ProfileImpl::FromBrowserContext(browser_context);
if (!profile)
return nullptr;
return profile->download_delegate();
}
DownloadDelegate* DownloadManagerDelegateImpl::GetDelegate(
download::DownloadItem* item) {
auto* browser_context = content::DownloadItemUtils::GetBrowserContext(item);
return GetDelegate(browser_context);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/download_manager_delegate_impl.cc | C++ | unknown | 11,440 |
// 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_DOWNLOAD_MANAGER_DELEGATE_IMPL_H_
#define WEBLAYER_BROWSER_DOWNLOAD_MANAGER_DELEGATE_IMPL_H_
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "components/download/public/common/download_item.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/download_manager_delegate.h"
namespace weblayer {
class DownloadDelegate;
extern const char kDownloadNextIDPref[];
class DownloadManagerDelegateImpl : public content::DownloadManagerDelegate,
public content::DownloadManager::Observer,
public download::DownloadItem::Observer {
public:
explicit DownloadManagerDelegateImpl(
content::DownloadManager* download_manager);
DownloadManagerDelegateImpl(const DownloadManagerDelegateImpl&) = delete;
DownloadManagerDelegateImpl& operator=(const DownloadManagerDelegateImpl&) =
delete;
~DownloadManagerDelegateImpl() override;
void set_download_dropped_closure_for_testing(
const base::RepeatingClosure& callback) {
download_dropped_callback_ = callback;
}
private:
// content::DownloadManagerDelegate implementation:
void GetNextId(content::DownloadIdCallback callback) override;
bool DetermineDownloadTarget(
download::DownloadItem* item,
content::DownloadTargetCallback* callback) override;
bool InterceptDownloadIfApplicable(
const GURL& url,
const std::string& user_agent,
const std::string& content_disposition,
const std::string& mime_type,
const std::string& request_origin,
int64_t content_length,
bool is_transient,
content::WebContents* web_contents) override;
void GetSaveDir(content::BrowserContext* browser_context,
base::FilePath* website_save_dir,
base::FilePath* download_save_dir) override;
void CheckDownloadAllowed(
const content::WebContents::Getter& web_contents_getter,
const GURL& url,
const std::string& request_method,
absl::optional<url::Origin> request_initiator,
bool from_download_cross_origin_redirect,
bool content_initiated,
content::CheckDownloadAllowedCallback check_download_allowed_cb) override;
// content::DownloadManager::Observer implementation:
void OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) override;
void OnDownloadDropped(content::DownloadManager* manager) override;
void OnManagerInitialized() override;
// download::DownloadItem::Observer implementation:
void OnDownloadUpdated(download::DownloadItem* item) override;
void OnDownloadPathGenerated(uint32_t download_id,
content::DownloadTargetCallback callback,
const base::FilePath& suggested_path);
void RemoveItem(const std::string& guid);
// Helper methods to get a DownloadDelegate.
DownloadDelegate* GetDelegate(content::WebContents* web_contents);
DownloadDelegate* GetDelegate(content::BrowserContext* browser_context);
DownloadDelegate* GetDelegate(download::DownloadItem* item);
raw_ptr<content::DownloadManager> download_manager_;
base::RepeatingClosure download_dropped_callback_;
base::WeakPtrFactory<DownloadManagerDelegateImpl> weak_ptr_factory_{this};
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_DOWNLOAD_MANAGER_DELEGATE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/download_manager_delegate_impl.h | C++ | unknown | 3,648 |
// 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/error_page_callback_proxy.h"
#include "base/android/jni_string.h"
#include "url/gurl.h"
#include "weblayer/browser/java/jni/ErrorPageCallbackProxy_jni.h"
#include "weblayer/browser/navigation_impl.h"
#include "weblayer/public/error_page.h"
#include "weblayer/public/tab.h"
using base::android::AttachCurrentThread;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
ErrorPageCallbackProxy::ErrorPageCallbackProxy(JNIEnv* env,
jobject obj,
Tab* tab)
: tab_(tab), java_impl_(env, obj) {
tab_->SetErrorPageDelegate(this);
}
ErrorPageCallbackProxy::~ErrorPageCallbackProxy() {
tab_->SetErrorPageDelegate(nullptr);
}
bool ErrorPageCallbackProxy::OnBackToSafety() {
JNIEnv* env = AttachCurrentThread();
return Java_ErrorPageCallbackProxy_onBackToSafety(env, java_impl_);
}
std::unique_ptr<ErrorPage> ErrorPageCallbackProxy::GetErrorPageContent(
Navigation* navigation) {
JNIEnv* env = AttachCurrentThread();
auto error_string = Java_ErrorPageCallbackProxy_getErrorPageContent(
env, java_impl_,
static_cast<NavigationImpl*>(navigation)->java_navigation());
if (!error_string)
return nullptr;
auto error_page = std::make_unique<ErrorPage>();
error_page->html = ConvertJavaStringToUTF8(env, error_string);
return error_page;
}
static jlong JNI_ErrorPageCallbackProxy_CreateErrorPageCallbackProxy(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& proxy,
jlong tab) {
return reinterpret_cast<jlong>(
new ErrorPageCallbackProxy(env, proxy, reinterpret_cast<Tab*>(tab)));
}
static void JNI_ErrorPageCallbackProxy_DeleteErrorPageCallbackProxy(
JNIEnv* env,
jlong proxy) {
delete reinterpret_cast<ErrorPageCallbackProxy*>(proxy);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/error_page_callback_proxy.cc | C++ | unknown | 2,010 |
// 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_ERROR_PAGE_CALLBACK_PROXY_H_
#define WEBLAYER_BROWSER_ERROR_PAGE_CALLBACK_PROXY_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "base/memory/raw_ptr.h"
#include "weblayer/public/error_page_delegate.h"
namespace weblayer {
class Tab;
// ErrorPageCallbackProxy forwards all ErrorPageDelegate functions to the Java
// side. There is one ErrorPageCallbackProxy per Tab.
class ErrorPageCallbackProxy : public ErrorPageDelegate {
public:
ErrorPageCallbackProxy(JNIEnv* env, jobject obj, Tab* tab);
ErrorPageCallbackProxy(const ErrorPageCallbackProxy&) = delete;
ErrorPageCallbackProxy& operator=(const ErrorPageCallbackProxy&) = delete;
~ErrorPageCallbackProxy() override;
// ErrorPageDelegate:
bool OnBackToSafety() override;
std::unique_ptr<ErrorPage> GetErrorPageContent(
Navigation* navigation) override;
private:
raw_ptr<Tab> tab_;
base::android::ScopedJavaGlobalRef<jobject> java_impl_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_ERROR_PAGE_CALLBACK_PROXY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/error_page_callback_proxy.h | C++ | unknown | 1,201 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/raw_ptr.h"
#include "weblayer/test/weblayer_browser_test.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "components/embedder_support/switches.h"
#include "components/error_page/content/browser/net_error_auto_reloader.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/url_loader_interceptor.h"
#include "net/test/url_request/url_request_failed_job.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/navigation_controller.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
#if BUILDFLAG(IS_ANDROID)
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
#endif
namespace weblayer {
using ErrorPageBrowserTest = WebLayerBrowserTest;
IN_PROC_BROWSER_TEST_F(ErrorPageBrowserTest, NameNotResolved) {
GURL error_page_url =
net::URLRequestFailedJob::GetMockHttpUrl(net::ERR_NAME_NOT_RESOLVED);
NavigateAndWaitForFailure(error_page_url, shell());
// Currently, interstitials for error pages are displayed only on Android.
#if BUILDFLAG(IS_ANDROID)
std::u16string expected_title =
l10n_util::GetStringUTF16(IDS_ANDROID_ERROR_PAGE_WEBPAGE_NOT_AVAILABLE);
EXPECT_EQ(expected_title, GetTitle(shell()));
#endif
}
// Verifies that navigating to a URL that returns a 404 with an empty body
// results in the navigation failing.
IN_PROC_BROWSER_TEST_F(ErrorPageBrowserTest, 404WithEmptyBody) {
EXPECT_TRUE(embedded_test_server()->Start());
GURL error_page_url = embedded_test_server()->GetURL("/empty404.html");
NavigateAndWaitForFailure(error_page_url, shell());
}
class ErrorPageReloadBrowserTest : public ErrorPageBrowserTest {
public:
ErrorPageReloadBrowserTest() = default;
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(embedder_support::kEnableAutoReload);
ErrorPageBrowserTest::SetUpCommandLine(command_line);
}
// Helper to perform navigations, whether successful or intercepted for
// simulated failure. Note that this asynchronously initiates the navigation
// and then waits only for the *navigation* to finish; this is in contrast to
// common test utilities which wait for loading to finish. It matters because
// most of NetErrorAutoReloader's interesting behavior is triggered at
// navigation completion and tests may want to observe the immediate side
// effects, such as the scheduling of an auto-reload timer.
//
// Return true if the navigation was successful, or false if it failed.
[[nodiscard]] bool Navigate(const GURL& url,
bool disable_network_error_auto_reload = false) {
content::TestNavigationManager navigation(web_contents(), url);
NavigationController::NavigateParams params;
auto* navigation_controller = shell()->tab()->GetNavigationController();
std::unique_ptr<DisableAutoReload> disable_auto_reload;
if (disable_network_error_auto_reload)
disable_auto_reload =
std::make_unique<DisableAutoReload>(navigation_controller);
navigation_controller->Navigate(url, params);
EXPECT_TRUE(navigation.WaitForNavigationFinished());
return navigation.was_successful();
}
// Returns the time-delay of the currently scheduled auto-reload task, if one
// is scheduled. If no auto-reload is scheduled, this returns null.
absl::optional<base::TimeDelta> GetCurrentAutoReloadDelay() {
auto* auto_reloader =
error_page::NetErrorAutoReloader::FromWebContents(web_contents());
if (!auto_reloader)
return absl::nullopt;
const absl::optional<base::OneShotTimer>& timer =
auto_reloader->next_reload_timer_for_testing();
if (!timer)
return absl::nullopt;
return timer->GetCurrentDelay();
}
content::WebContents* web_contents() {
return static_cast<TabImpl*>(shell()->tab())->web_contents();
}
private:
class DisableAutoReload : public NavigationObserver {
public:
explicit DisableAutoReload(NavigationController* controller)
: controller_(controller) {
controller_->AddObserver(this);
}
~DisableAutoReload() override { controller_->RemoveObserver(this); }
// NavigationObserver implementation:
void NavigationStarted(Navigation* navigation) override {
navigation->DisableNetworkErrorAutoReload();
}
private:
raw_ptr<NavigationController> controller_;
};
};
IN_PROC_BROWSER_TEST_F(ErrorPageReloadBrowserTest, ReloadOnNetworkChanged) {
ASSERT_TRUE(embedded_test_server()->Start());
// Ensure that the NetErrorAutoReloader believes it's online, otherwise it
// does not attempt auto-reload on error pages.
error_page::NetErrorAutoReloader::CreateForWebContents(web_contents());
auto* reloader =
error_page::NetErrorAutoReloader::FromWebContents(web_contents());
reloader->DisableConnectionChangeObservationForTesting();
reloader->OnConnectionChanged(network::mojom::ConnectionType::CONNECTION_4G);
GURL url = embedded_test_server()->GetURL("/error_page");
// We send net::ERR_NETWORK_CHANGED on the first load, and the reload should
// get a net::OK response.
bool first_try = true;
content::URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
[&url, &first_try](content::URLLoaderInterceptor::RequestParams* params) {
if (params->url_request.url == url) {
if (first_try) {
first_try = false;
params->client->OnComplete(
network::URLLoaderCompletionStatus(net::ERR_NETWORK_CHANGED));
} else {
content::URLLoaderInterceptor::WriteResponse(
"weblayer/test/data/simple_page.html", params->client.get());
}
return true;
}
return false;
}));
NavigateAndWaitForCompletion(url, shell());
}
// By default auto reload is enabled.
IN_PROC_BROWSER_TEST_F(ErrorPageReloadBrowserTest, AutoReloadDefault) {
ASSERT_TRUE(embedded_test_server()->Start());
// Ensure that the NetErrorAutoReloader believes it's online, otherwise it
// does not attempt auto-reload on error pages.
error_page::NetErrorAutoReloader::CreateForWebContents(web_contents());
auto* reloader =
error_page::NetErrorAutoReloader::FromWebContents(web_contents());
reloader->DisableConnectionChangeObservationForTesting();
reloader->OnConnectionChanged(network::mojom::ConnectionType::CONNECTION_4G);
GURL url = embedded_test_server()->GetURL("/error_page");
content::URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
[&url](content::URLLoaderInterceptor::RequestParams* params) {
if (params->url_request.url == url) {
params->client->OnComplete(
network::URLLoaderCompletionStatus(net::ERR_NETWORK_CHANGED));
return true;
}
return false;
}));
EXPECT_FALSE(Navigate(url));
EXPECT_EQ(error_page::NetErrorAutoReloader::GetNextReloadDelayForTesting(0),
GetCurrentAutoReloadDelay());
}
IN_PROC_BROWSER_TEST_F(ErrorPageReloadBrowserTest, AutoReloadDisabled) {
ASSERT_TRUE(embedded_test_server()->Start());
GURL url = embedded_test_server()->GetURL("/error_page");
content::URLLoaderInterceptor interceptor(base::BindLambdaForTesting(
[&url](content::URLLoaderInterceptor::RequestParams* params) {
if (params->url_request.url == url) {
params->client->OnComplete(
network::URLLoaderCompletionStatus(net::ERR_NETWORK_CHANGED));
return true;
}
return false;
}));
EXPECT_FALSE(Navigate(url, true));
EXPECT_EQ(absl::nullopt, GetCurrentAutoReloadDelay());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/errorpage_browsertest.cc | C++ | unknown | 7,914 |
// 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/favicon/favicon_backend_wrapper.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/task/sequenced_task_runner.h"
#include "components/favicon/core/favicon_backend.h"
#include "components/favicon/core/favicon_database.h"
namespace weblayer {
// Removing out of date entries can be costly. To avoid blocking the thread
// this code runs on, the work is potentially throttled. Specifically at
// most |kMaxNumberOfEntriesToRemoveAtATime| are removed during a single call.
// If |kMaxNumberOfEntriesToRemoveAtATime| are removed, then there may be more
// entries that can be removed, so the timer is restarted with a shorter time
// out (|kTimeDeltaForRunningExpireWithRemainingWork|).
constexpr base::TimeDelta kTimeDeltaForRunningExpireNoRemainingWork =
base::Hours(1);
constexpr int kMaxNumberOfEntriesToRemoveAtATime = 100;
FaviconBackendWrapper::FaviconBackendWrapper(
scoped_refptr<base::SequencedTaskRunner> task_runner)
: base::RefCountedDeleteOnSequence<FaviconBackendWrapper>(task_runner),
task_runner_(task_runner) {}
void FaviconBackendWrapper::Init(const base::FilePath& db_path) {
db_path_ = db_path;
favicon_backend_ = favicon::FaviconBackend::Create(db_path, this);
if (!favicon_backend_) {
LOG(WARNING) << "Could not initialize the favicon database.";
// The favicon db is not critical. On failure initializing try deleting
// the file and repeating. Note that FaviconDatabase already tries to
// initialize twice.
base::DeleteFile(db_path);
favicon_backend_ = favicon::FaviconBackend::Create(db_path, this);
if (!favicon_backend_) {
LOG(WARNING) << "Could not initialize db second time, giving up.";
return;
}
}
expire_timer_.Start(FROM_HERE, kTimeDeltaForRunningExpireWithRemainingWork,
this, &FaviconBackendWrapper::OnExpireTimerFired);
}
void FaviconBackendWrapper::Shutdown() {
// Ensures there isn't a reference to this in the task runner (by way of the
// task the timer posts).
commit_timer_.Stop();
expire_timer_.Stop();
}
void FaviconBackendWrapper::DeleteAndRecreateDatabase() {
Shutdown();
favicon_backend_.reset();
base::DeleteFile(db_path_);
Init(db_path_);
}
std::vector<favicon_base::FaviconRawBitmapResult>
FaviconBackendWrapper::GetFaviconsForUrl(
const GURL& page_url,
const favicon_base::IconTypeSet& icon_types,
const std::vector<int>& desired_sizes) {
if (!favicon_backend_)
return {};
return favicon_backend_->GetFaviconsForUrl(page_url, icon_types,
desired_sizes,
/* fallback_to_host */ false);
}
favicon_base::FaviconRawBitmapResult
FaviconBackendWrapper::GetLargestFaviconForUrl(
const GURL& page_url,
const std::vector<favicon_base::IconTypeSet>& icon_types_list,
int minimum_size_in_pixels) {
if (!favicon_backend_)
return {};
return favicon_backend_->GetLargestFaviconForUrl(page_url, icon_types_list,
minimum_size_in_pixels);
}
void FaviconBackendWrapper::SetFaviconsOutOfDateForPage(const GURL& page_url) {
if (favicon_backend_ &&
favicon_backend_->SetFaviconsOutOfDateForPage(page_url)) {
ScheduleCommit();
}
}
void FaviconBackendWrapper::SetFavicons(const base::flat_set<GURL>& page_urls,
favicon_base::IconType icon_type,
const GURL& icon_url,
const std::vector<SkBitmap>& bitmaps) {
if (favicon_backend_ &&
favicon_backend_
->SetFavicons(page_urls, icon_type, icon_url, bitmaps,
favicon::FaviconBitmapType::ON_VISIT)
.did_change_database()) {
ScheduleCommit();
}
}
void FaviconBackendWrapper::CloneFaviconMappingsForPages(
const GURL& page_url_to_read,
const favicon_base::IconTypeSet& icon_types,
const base::flat_set<GURL>& page_urls_to_write) {
if (!favicon_backend_)
return;
std::set<GURL> changed_urls = favicon_backend_->CloneFaviconMappingsForPages(
{page_url_to_read}, icon_types, page_urls_to_write);
if (!changed_urls.empty())
ScheduleCommit();
}
std::vector<favicon_base::FaviconRawBitmapResult>
FaviconBackendWrapper::GetFavicon(const GURL& icon_url,
favicon_base::IconType icon_type,
const std::vector<int>& desired_sizes) {
return UpdateFaviconMappingsAndFetch({}, icon_url, icon_type, desired_sizes);
}
std::vector<favicon_base::FaviconRawBitmapResult>
FaviconBackendWrapper::UpdateFaviconMappingsAndFetch(
const base::flat_set<GURL>& page_urls,
const GURL& icon_url,
favicon_base::IconType icon_type,
const std::vector<int>& desired_sizes) {
if (!favicon_backend_)
return {};
auto result = favicon_backend_->UpdateFaviconMappingsAndFetch(
page_urls, icon_url, icon_type, desired_sizes);
if (!result.updated_page_urls.empty())
ScheduleCommit();
return result.bitmap_results;
}
void FaviconBackendWrapper::DeleteFaviconMappings(
const base::flat_set<GURL>& page_urls,
favicon_base::IconType icon_type) {
if (!favicon_backend_)
return;
auto deleted_page_urls =
favicon_backend_->DeleteFaviconMappings(page_urls, icon_type);
if (!deleted_page_urls.empty())
ScheduleCommit();
}
std::vector<GURL> FaviconBackendWrapper::GetCachedRecentRedirectsForPage(
const GURL& page_url) {
// By only returning |page_url| this code won't set the favicon on redirects.
// If that becomes necessary, we would need this class to know about
// redirects. Chrome does this by way of HistoryService remembering redirects
// for recent pages. See |HistoryBackend::recent_redirects_|.
return {page_url};
}
FaviconBackendWrapper::~FaviconBackendWrapper() = default;
void FaviconBackendWrapper::ScheduleCommit() {
if (!commit_timer_.IsRunning()) {
// 10 seconds matches that of HistoryBackend.
commit_timer_.Start(FROM_HERE, base::Seconds(10), this,
&FaviconBackendWrapper::Commit);
}
}
void FaviconBackendWrapper::Commit() {
if (favicon_backend_)
favicon_backend_->Commit();
}
void FaviconBackendWrapper::OnExpireTimerFired() {
if (!favicon_backend_)
return;
// See comments above |kTimeDeltaForRunningExpireNoRemainingWork| for a
// description of this logic.
favicon::FaviconDatabase* db = favicon_backend_->db();
auto icon_ids = db->GetFaviconsLastUpdatedBefore(
base::Time::Now() - kTimeDeltaWhenEntriesAreRemoved,
kMaxNumberOfEntriesToRemoveAtATime);
for (favicon_base::FaviconID icon_id : icon_ids) {
db->DeleteFavicon(icon_id);
db->DeleteIconMappingsForFaviconId(icon_id);
}
if (!icon_ids.empty())
Commit();
const base::TimeDelta delta =
icon_ids.size() == kMaxNumberOfEntriesToRemoveAtATime
? kTimeDeltaForRunningExpireWithRemainingWork
: kTimeDeltaForRunningExpireNoRemainingWork;
expire_timer_.Start(FROM_HERE, delta, this,
&FaviconBackendWrapper::OnExpireTimerFired);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_backend_wrapper.cc | C++ | unknown | 7,370 |
// 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_FAVICON_FAVICON_BACKEND_WRAPPER_H_
#define WEBLAYER_BROWSER_FAVICON_FAVICON_BACKEND_WRAPPER_H_
#include <memory>
#include <vector>
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/memory/ref_counted_delete_on_sequence.h"
#include "base/timer/timer.h"
#include "components/favicon/core/favicon_backend_delegate.h"
#include "components/favicon_base/favicon_types.h"
class GURL;
namespace base {
class FilePath;
class SequencedTaskRunner;
} // namespace base
namespace favicon {
class FaviconBackend;
}
namespace weblayer {
// FaviconBackendWrapper runs on a background task-runner and owns the database
// side of favicons. This class largely delegates to favicon::FaviconBackend.
class FaviconBackendWrapper
: public base::RefCountedDeleteOnSequence<FaviconBackendWrapper>,
public favicon::FaviconBackendDelegate {
public:
explicit FaviconBackendWrapper(
scoped_refptr<base::SequencedTaskRunner> task_runner);
FaviconBackendWrapper(const FaviconBackendWrapper&) = delete;
FaviconBackendWrapper& operator=(const FaviconBackendWrapper&) = delete;
void Init(const base::FilePath& db_path);
void Shutdown();
void DeleteAndRecreateDatabase();
// All of these functions are called by the FaviconServiceImpl. They call
// through to |favicon_backend_|.
std::vector<favicon_base::FaviconRawBitmapResult> GetFaviconsForUrl(
const GURL& page_url,
const favicon_base::IconTypeSet& icon_types,
const std::vector<int>& desired_sizes);
favicon_base::FaviconRawBitmapResult GetLargestFaviconForUrl(
const GURL& page_url,
const std::vector<favicon_base::IconTypeSet>& icon_types_list,
int minimum_size_in_pixels);
void SetFaviconsOutOfDateForPage(const GURL& page_url);
void SetFavicons(const base::flat_set<GURL>& page_urls,
favicon_base::IconType icon_type,
const GURL& icon_url,
const std::vector<SkBitmap>& bitmaps);
void CloneFaviconMappingsForPages(
const GURL& page_url_to_read,
const favicon_base::IconTypeSet& icon_types,
const base::flat_set<GURL>& page_urls_to_write);
std::vector<favicon_base::FaviconRawBitmapResult> GetFavicon(
const GURL& icon_url,
favicon_base::IconType icon_type,
const std::vector<int>& desired_sizes);
std::vector<favicon_base::FaviconRawBitmapResult>
UpdateFaviconMappingsAndFetch(const base::flat_set<GURL>& page_urls,
const GURL& icon_url,
favicon_base::IconType icon_type,
const std::vector<int>& desired_sizes);
void DeleteFaviconMappings(const base::flat_set<GURL>& page_urls,
favicon_base::IconType icon_type);
// favicon::FaviconBackendDelegate:
std::vector<GURL> GetCachedRecentRedirectsForPage(
const GURL& page_url) override;
private:
friend class base::RefCountedDeleteOnSequence<FaviconBackendWrapper>;
friend class base::DeleteHelper<FaviconBackendWrapper>;
friend class FaviconBackendWrapperTest;
~FaviconBackendWrapper() override;
void ScheduleCommit();
void Commit();
// Called to expire (remove) out of date icons and restart the timer.
void OnExpireTimerFired();
scoped_refptr<base::SequencedTaskRunner> task_runner_;
// Timer used to delay commits for a short amount of time. This done to
// batch commits.
base::OneShotTimer commit_timer_;
// The real implementation of the backend. If there is a problem
// initializing the database this will be null.
std::unique_ptr<favicon::FaviconBackend> favicon_backend_;
// Timer used to remove items from the database that are likely no longer
// needed.
base::OneShotTimer expire_timer_;
base::FilePath db_path_;
};
// These values are here only for tests.
// Amount of time before favicons are removed. That is, any favicons downloaded
// before this amount of time are removed.
constexpr base::TimeDelta kTimeDeltaWhenEntriesAreRemoved = base::Days(30);
// See comment near kMaxNumberOfEntriesToRemoveAtATime for details on this.
constexpr base::TimeDelta kTimeDeltaForRunningExpireWithRemainingWork =
base::Minutes(2);
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FAVICON_FAVICON_BACKEND_WRAPPER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_backend_wrapper.h | C++ | unknown | 4,484 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "weblayer/browser/favicon/favicon_backend_wrapper.h"
#include <vector>
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/ref_counted_memory.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "components/favicon/core/favicon_backend.h"
#include "components/favicon/core/favicon_database.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace weblayer {
namespace {
// Blobs for adding favicons.
const unsigned char kBlob1[] =
"12346102356120394751634516591348710478123649165419234519234512349134";
} // namespace
class FaviconBackendWrapperTest : public testing::Test {
protected:
favicon::FaviconBackend* backend() {
return wrapper_->favicon_backend_.get();
}
// testing::Test:
void SetUp() override {
// Get a temporary directory for the test DB files.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
db_path_ = temp_dir_.GetPath().AppendASCII("test_db");
}
void TearDown() override {
wrapper_ = nullptr;
testing::Test::TearDown();
}
base::test::SingleThreadTaskEnvironment task_environment_{
base::test::TaskEnvironment::TimeSource::MOCK_TIME};
base::ScopedTempDir temp_dir_;
base::FilePath db_path_;
scoped_refptr<FaviconBackendWrapper> wrapper_;
};
TEST_F(FaviconBackendWrapperTest, BasicExpire) {
wrapper_ = base::MakeRefCounted<FaviconBackendWrapper>(
base::SingleThreadTaskRunner::GetCurrentDefault());
wrapper_->Init(db_path_);
ASSERT_TRUE(backend());
auto* db = backend()->db();
std::vector<unsigned char> data(kBlob1, kBlob1 + sizeof(kBlob1));
scoped_refptr<base::RefCountedBytes> favicon(new base::RefCountedBytes(data));
GURL url("http://google.com");
const base::Time time1 = base::Time::Now();
favicon_base::FaviconID favicon_id1 =
db->AddFavicon(url, favicon_base::IconType::kTouchIcon, favicon,
favicon::FaviconBitmapType::ON_VISIT, time1, gfx::Size());
ASSERT_NE(0, favicon_id1);
favicon::IconMappingID icon_mapping_id1 =
db->AddIconMapping(url, favicon_id1);
ASSERT_NE(0, icon_mapping_id1);
// Fast forward past first expire running.
task_environment_.FastForwardBy(kTimeDeltaForRunningExpireWithRemainingWork *
2);
// The icon should still be there.
EXPECT_TRUE(db->GetFaviconHeader(favicon_id1, nullptr, nullptr));
EXPECT_TRUE(db->HasMappingFor(favicon_id1));
// Fast forward such that the icon is removed.
task_environment_.FastForwardBy(kTimeDeltaWhenEntriesAreRemoved);
EXPECT_FALSE(db->GetFaviconHeader(favicon_id1, nullptr, nullptr));
EXPECT_FALSE(db->HasMappingFor(favicon_id1));
}
TEST_F(FaviconBackendWrapperTest, ExpireWithOneRemaining) {
wrapper_ = base::MakeRefCounted<FaviconBackendWrapper>(
base::SingleThreadTaskRunner::GetCurrentDefault());
wrapper_->Init(db_path_);
ASSERT_TRUE(backend());
auto* db = backend()->db();
// Add two entries. The second is more recent then the first.
std::vector<unsigned char> data(kBlob1, kBlob1 + sizeof(kBlob1));
scoped_refptr<base::RefCountedBytes> favicon(new base::RefCountedBytes(data));
GURL url("http://google.com");
const base::Time time1 = base::Time::Now();
favicon_base::FaviconID favicon_id1 =
db->AddFavicon(url, favicon_base::IconType::kTouchIcon, favicon,
favicon::FaviconBitmapType::ON_VISIT, time1, gfx::Size());
ASSERT_NE(0, favicon_id1);
favicon::IconMappingID icon_mapping_id1 =
db->AddIconMapping(url, favicon_id1);
ASSERT_NE(0, icon_mapping_id1);
const base::Time time2 = time1 + kTimeDeltaWhenEntriesAreRemoved / 2;
favicon_base::FaviconID favicon_id2 =
db->AddFavicon(url, favicon_base::IconType::kTouchIcon, favicon,
favicon::FaviconBitmapType::ON_VISIT, time2, gfx::Size());
ASSERT_NE(0, favicon_id2);
favicon::IconMappingID icon_mapping_id2 =
db->AddIconMapping(url, favicon_id2);
ASSERT_NE(0, icon_mapping_id2);
// Fast forward such the first entry is expired and should be removed, but
// not the second.
task_environment_.FastForwardBy(kTimeDeltaWhenEntriesAreRemoved +
base::Days(1));
EXPECT_FALSE(db->GetFaviconHeader(favicon_id1, nullptr, nullptr));
EXPECT_FALSE(db->HasMappingFor(favicon_id1));
EXPECT_TRUE(db->GetFaviconHeader(favicon_id2, nullptr, nullptr));
EXPECT_TRUE(db->HasMappingFor(favicon_id2));
// Fast forward enough such that second is removed.
task_environment_.FastForwardBy(kTimeDeltaWhenEntriesAreRemoved +
base::Days(1));
EXPECT_FALSE(db->GetFaviconHeader(favicon_id2, nullptr, nullptr));
EXPECT_FALSE(db->HasMappingFor(favicon_id2));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_backend_wrapper_unittest.cc | C++ | unknown | 4,974 |
// 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/favicon/favicon_callback_proxy.h"
#include "base/android/jni_string.h"
#include "ui/gfx/android/java_bitmap.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "url/gurl.h"
#include "weblayer/browser/java/jni/FaviconCallbackProxy_jni.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/favicon_fetcher.h"
namespace weblayer {
FaviconCallbackProxy::FaviconCallbackProxy(JNIEnv* env, jobject obj, Tab* tab)
: java_proxy_(env, obj),
favicon_fetcher_(tab->CreateFaviconFetcher(this)) {}
FaviconCallbackProxy::~FaviconCallbackProxy() = default;
void FaviconCallbackProxy::OnFaviconChanged(const gfx::Image& image) {
SkBitmap favicon = image.AsImageSkia().GetRepresentation(1.0f).GetBitmap();
JNIEnv* env = base::android::AttachCurrentThread();
Java_FaviconCallbackProxy_onFaviconChanged(
env, java_proxy_,
favicon.empty() ? nullptr : gfx::ConvertToJavaBitmap(favicon));
}
static jlong JNI_FaviconCallbackProxy_CreateFaviconCallbackProxy(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& proxy,
jlong tab) {
return reinterpret_cast<jlong>(
new FaviconCallbackProxy(env, proxy, reinterpret_cast<TabImpl*>(tab)));
}
static void JNI_FaviconCallbackProxy_DeleteFaviconCallbackProxy(JNIEnv* env,
jlong proxy) {
delete reinterpret_cast<FaviconCallbackProxy*>(proxy);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_callback_proxy.cc | C++ | unknown | 1,669 |
// 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_FAVICON_FAVICON_CALLBACK_PROXY_H_
#define WEBLAYER_BROWSER_FAVICON_FAVICON_CALLBACK_PROXY_H_
#include <memory>
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "weblayer/public/favicon_fetcher_delegate.h"
namespace weblayer {
class FaviconFetcher;
class Tab;
// FullscreenCallbackProxy forwards all FullscreenDelegate functions to the
// Java side. There is at most one FullscreenCallbackProxy per Tab.
class FaviconCallbackProxy : public FaviconFetcherDelegate {
public:
FaviconCallbackProxy(JNIEnv* env, jobject obj, Tab* tab);
FaviconCallbackProxy(const FaviconCallbackProxy&) = delete;
FaviconCallbackProxy& operator=(const FaviconCallbackProxy&) = delete;
~FaviconCallbackProxy() override;
// FaviconFetcherDelegate:
void OnFaviconChanged(const gfx::Image& image) override;
private:
base::android::ScopedJavaGlobalRef<jobject> java_proxy_;
std::unique_ptr<FaviconFetcher> favicon_fetcher_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FAVICON_FAVICON_CALLBACK_PROXY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_callback_proxy.h | C++ | unknown | 1,201 |
// 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/favicon/favicon_fetcher_impl.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "components/favicon/content/content_favicon_driver.h"
#include "ui/gfx/image/image.h"
#include "weblayer/browser/browser_context_impl.h"
#include "weblayer/browser/favicon/favicon_fetcher_impl.h"
#include "weblayer/browser/favicon/favicon_service_impl.h"
#include "weblayer/browser/favicon/favicon_service_impl_factory.h"
#include "weblayer/browser/favicon/favicon_service_impl_observer.h"
#include "weblayer/browser/favicon/test_favicon_fetcher_delegate.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/browser.h"
#include "weblayer/public/favicon_fetcher_delegate.h"
#include "weblayer/public/navigation_controller.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 {
// FaviconServiceImplObserver used to wait for download to fail.
class TestFaviconServiceImplObserver : public FaviconServiceImplObserver {
public:
void Wait() {
ASSERT_EQ(nullptr, run_loop_.get());
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
run_loop_.reset();
}
// FaviconServiceImplObserver:
void OnUnableToDownloadFavicon() override {
if (run_loop_)
run_loop_->Quit();
}
private:
std::unique_ptr<base::RunLoop> run_loop_;
};
} // namespace
using FaviconFetcherBrowserTest = WebLayerBrowserTest;
IN_PROC_BROWSER_TEST_F(FaviconFetcherBrowserTest, Basic) {
ASSERT_TRUE(embedded_test_server()->Start());
TestFaviconFetcherDelegate fetcher_delegate;
auto fetcher = shell()->tab()->CreateFaviconFetcher(&fetcher_delegate);
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL(
"/simple_page_with_favicon_and_before_unload.html"),
shell());
fetcher_delegate.WaitForFavicon();
EXPECT_FALSE(fetcher_delegate.last_image().IsEmpty());
EXPECT_EQ(fetcher_delegate.last_image(), fetcher->GetFavicon());
EXPECT_EQ(1, fetcher_delegate.on_favicon_changed_call_count());
fetcher_delegate.ClearLastImage();
const GURL url2 =
embedded_test_server()->GetURL("/simple_page_with_favicon.html");
shell()->tab()->GetNavigationController()->Navigate(url2);
// Favicon doesn't change immediately on navigation.
EXPECT_FALSE(fetcher->GetFavicon().IsEmpty());
// Favicon does change once start is received.
TestNavigationObserver test_observer(
url2, TestNavigationObserver::NavigationEvent::kStart, shell());
test_observer.Wait();
EXPECT_TRUE(fetcher_delegate.last_image().IsEmpty());
fetcher_delegate.WaitForNonemptyFavicon();
EXPECT_FALSE(fetcher_delegate.last_image().IsEmpty());
EXPECT_EQ(fetcher_delegate.last_image(), fetcher->GetFavicon());
// OnFaviconChanged() is called twice, once with an empty image (because of
// the navigation), the second with the real image.
EXPECT_EQ(2, fetcher_delegate.on_favicon_changed_call_count());
}
IN_PROC_BROWSER_TEST_F(FaviconFetcherBrowserTest, NavigateToPageWithNoFavicon) {
ASSERT_TRUE(embedded_test_server()->Start());
TestFaviconFetcherDelegate fetcher_delegate;
auto fetcher = shell()->tab()->CreateFaviconFetcher(&fetcher_delegate);
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page_with_favicon.html"),
shell());
fetcher_delegate.WaitForFavicon();
fetcher_delegate.ClearLastImage();
TestFaviconServiceImplObserver test_observer;
FaviconServiceImplFactory::GetForBrowserContext(
static_cast<TabImpl*>(shell()->tab())->profile()->GetBrowserContext())
->set_observer(&test_observer);
const GURL url2 = embedded_test_server()->GetURL("/simple_page.html");
shell()->tab()->GetNavigationController()->Navigate(url2);
EXPECT_TRUE(fetcher_delegate.last_image().IsEmpty());
// The delegate should be notified of the empty image once.
test_observer.Wait();
EXPECT_TRUE(fetcher_delegate.last_image().IsEmpty());
EXPECT_EQ(1, fetcher_delegate.on_favicon_changed_call_count());
}
IN_PROC_BROWSER_TEST_F(FaviconFetcherBrowserTest,
ContentFaviconDriverLifetime) {
ASSERT_TRUE(embedded_test_server()->Start());
content::WebContents* web_contents =
static_cast<TabImpl*>(shell()->tab())->web_contents();
// Drivers are immediately created for every tab.
auto* favicon_driver =
favicon::ContentFaviconDriver::FromWebContents(web_contents);
EXPECT_NE(nullptr, favicon_driver);
// Request a fetcher, which should trigger creating ContentFaviconDriver.
TestFaviconFetcherDelegate fetcher_delegate;
auto fetcher = shell()->tab()->CreateFaviconFetcher(&fetcher_delegate);
// Check that the driver has not changed.
EXPECT_EQ(favicon_driver,
favicon::ContentFaviconDriver::FromWebContents(web_contents));
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page_with_favicon.html"),
shell());
fetcher_delegate.WaitForFavicon();
EXPECT_FALSE(fetcher_delegate.last_image().IsEmpty());
}
// This test creates a Browser and Tab, which doesn't work well with Java when
// driven from native code.
#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(FaviconFetcherBrowserTest, OffTheRecord) {
auto otr_profile = Profile::Create(std::string(), true);
ProfileImpl* otr_profile_impl = static_cast<ProfileImpl*>(otr_profile.get());
EXPECT_TRUE(otr_profile_impl->GetBrowserContext()->IsOffTheRecord());
auto otr_browser = Browser::Create(otr_profile.get(), nullptr);
Tab* tab = otr_browser->CreateTab();
// There is no FaviconService for off the record profiles. FaviconService
// writes to disk, which is not appropriate for off the record mode.
EXPECT_EQ(nullptr, FaviconServiceImplFactory::GetForBrowserContext(
otr_profile_impl->GetBrowserContext()));
ASSERT_TRUE(embedded_test_server()->Start());
TestFaviconFetcherDelegate fetcher_delegate;
auto fetcher = tab->CreateFaviconFetcher(&fetcher_delegate);
NavigateAndWaitForCompletion(
embedded_test_server()->GetURL("/simple_page_with_favicon.html"), tab);
fetcher_delegate.WaitForFavicon();
EXPECT_FALSE(fetcher_delegate.last_image().IsEmpty());
EXPECT_EQ(fetcher_delegate.last_image(), fetcher->GetFavicon());
EXPECT_EQ(1, fetcher_delegate.on_favicon_changed_call_count());
}
#endif
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_fetcher_browsertest.cc | C++ | unknown | 6,654 |
// 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/favicon/favicon_fetcher_impl.h"
#include "ui/gfx/image/image.h"
#include "weblayer/browser/favicon/favicon_tab_helper.h"
#include "weblayer/public/favicon_fetcher_delegate.h"
#include "base/logging.h"
namespace weblayer {
FaviconFetcherImpl::FaviconFetcherImpl(content::WebContents* web_contents,
FaviconFetcherDelegate* delegate)
: web_contents_(web_contents),
observer_subscription_(FaviconTabHelper::FromWebContents(web_contents)
->RegisterFaviconFetcherDelegate(delegate)) {}
FaviconFetcherImpl::~FaviconFetcherImpl() = default;
gfx::Image FaviconFetcherImpl::GetFavicon() {
return FaviconTabHelper::FromWebContents(web_contents_)->favicon();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_fetcher_impl.cc | C++ | unknown | 936 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBLAYER_BROWSER_FAVICON_FAVICON_FETCHER_IMPL_H_
#define WEBLAYER_BROWSER_FAVICON_FAVICON_FETCHER_IMPL_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "weblayer/browser/favicon/favicon_tab_helper.h"
#include "weblayer/public/favicon_fetcher.h"
namespace content {
class WebContents;
}
namespace weblayer {
class FaviconFetcherDelegate;
// FaviconFetcher implementation that largely delegates to FaviconTabHelper
// for the real implementation.
class FaviconFetcherImpl : public FaviconFetcher {
public:
FaviconFetcherImpl(content::WebContents* web_contents,
FaviconFetcherDelegate* delegate);
FaviconFetcherImpl(const FaviconFetcherImpl&) = delete;
FaviconFetcherImpl& operator=(const FaviconFetcherImpl&) = delete;
~FaviconFetcherImpl() override;
// FaviconFetcher:
gfx::Image GetFavicon() override;
private:
raw_ptr<content::WebContents> web_contents_;
std::unique_ptr<FaviconTabHelper::ObserverSubscription>
observer_subscription_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FAVICON_FAVICON_FETCHER_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_fetcher_impl.h | C++ | unknown | 1,245 |
// 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/favicon/favicon_service_impl.h"
#include <stddef.h>
#include <vector>
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/hash/hash.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "build/build_config.h"
#include "components/favicon_base/favicon_util.h"
#include "components/favicon_base/select_favicon_frames.h"
#include "content/public/common/url_constants.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/favicon_size.h"
#include "url/gurl.h"
#include "weblayer/browser/favicon/favicon_backend_wrapper.h"
#include "weblayer/browser/favicon/favicon_service_impl_observer.h"
namespace weblayer {
namespace {
bool CanAddUrl(const GURL& url) {
if (!url.is_valid())
return false;
if (url.SchemeIs(url::kJavaScriptScheme) || url.SchemeIs(url::kAboutScheme) ||
url.SchemeIs(url::kContentScheme) ||
url.SchemeIs(content::kChromeDevToolsScheme) ||
url.SchemeIs(content::kChromeUIScheme) ||
url.SchemeIs(content::kViewSourceScheme)) {
return false;
}
return true;
}
// Returns the IconTypeSet for the current platform. This matches the set
// of favicon types that are requested for the platform (see
// FaviconDriverImpl).
favicon_base::IconTypeSet GetIconTypeSet() {
#if BUILDFLAG(IS_ANDROID)
return {favicon_base::IconType::kFavicon, favicon_base::IconType::kTouchIcon,
favicon_base::IconType::kTouchPrecomposedIcon,
favicon_base::IconType::kWebManifestIcon};
#else
return {favicon_base::IconType::kFavicon};
#endif
}
int GetDesiredFaviconSizeInDips() {
#if BUILDFLAG(IS_ANDROID)
// This is treatest as the largest available icon.
return 0;
#else
return gfx::kFaviconSize;
#endif
}
void OnGotFaviconsForPageUrl(
int desired_size_in_dip,
base::OnceCallback<void(gfx::Image)> callback,
std::vector<favicon_base::FaviconRawBitmapResult> results) {
favicon_base::FaviconImageResult image_result;
image_result.image = favicon_base::SelectFaviconFramesFromPNGs(
results, favicon_base::GetFaviconScales(), desired_size_in_dip);
favicon_base::SetFaviconColorSpace(&image_result.image);
std::move(callback).Run(image_result.image);
}
} // namespace
FaviconServiceImpl::FaviconServiceImpl() = default;
FaviconServiceImpl::~FaviconServiceImpl() {
backend_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::Shutdown, std::move(backend_)));
}
void FaviconServiceImpl::Init(const base::FilePath& db_path) {
if (!backend_task_runner_) {
// BLOCK_SHUTDOWN matches that of HistoryService. It's done in hopes of
// preventing database corruption.
backend_task_runner_ = base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::WithBaseSyncPrimitives(),
base::TaskPriority::USER_BLOCKING,
base::TaskShutdownBehavior::BLOCK_SHUTDOWN});
}
backend_ = base::MakeRefCounted<FaviconBackendWrapper>(backend_task_runner_);
backend_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::Init, backend_, db_path));
}
void FaviconServiceImpl::DeleteAndRecreateDatabase(base::OnceClosure callback) {
backend_task_runner_->PostTaskAndReply(
FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::DeleteAndRecreateDatabase,
backend_),
std::move(callback));
}
base::CancelableTaskTracker::TaskId FaviconServiceImpl::GetFaviconForPageUrl(
const GURL& page_url,
base::OnceCallback<void(gfx::Image)> callback,
base::CancelableTaskTracker* tracker) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// The arguments supplied to this function should return an image matching
// that returned by FaviconFetcher.
return tracker->PostTaskAndReplyWithResult(
backend_task_runner_.get(), FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::GetFaviconsForUrl, backend_,
page_url, GetIconTypeSet(),
GetDesiredFaviconSizesInPixels()),
base::BindOnce(&OnGotFaviconsForPageUrl, GetDesiredFaviconSizeInDips(),
std::move(callback)));
}
base::CancelableTaskTracker::TaskId
FaviconServiceImpl::GetLargestRawFaviconForPageURL(
const GURL& page_url,
const std::vector<favicon_base::IconTypeSet>& icon_types,
int minimum_size_in_pixels,
favicon_base::FaviconRawBitmapCallback callback,
base::CancelableTaskTracker* tracker) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return tracker->PostTaskAndReplyWithResult(
backend_task_runner_.get(), FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::GetLargestFaviconForUrl, backend_,
page_url, icon_types, minimum_size_in_pixels),
std::move(callback));
}
base::CancelableTaskTracker::TaskId FaviconServiceImpl::GetFaviconForPageURL(
const GURL& page_url,
const favicon_base::IconTypeSet& icon_types,
int desired_size_in_dip,
favicon_base::FaviconResultsCallback callback,
base::CancelableTaskTracker* tracker) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return tracker->PostTaskAndReplyWithResult(
backend_task_runner_.get(), FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::GetFaviconsForUrl, backend_,
page_url, icon_types,
GetPixelSizesForFaviconScales(desired_size_in_dip)),
std::move(callback));
}
void FaviconServiceImpl::SetFaviconOutOfDateForPage(const GURL& page_url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
backend_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::SetFaviconsOutOfDateForPage,
backend_, page_url));
}
void FaviconServiceImpl::SetFavicons(const base::flat_set<GURL>& page_urls,
const GURL& icon_url,
favicon_base::IconType icon_type,
const gfx::Image& image) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::flat_set<GURL> page_urls_to_save;
page_urls_to_save.reserve(page_urls.capacity());
for (const GURL& page_url : page_urls) {
if (CanAddUrl(page_url))
page_urls_to_save.insert(page_url);
}
if (page_urls_to_save.empty())
return;
backend_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&FaviconBackendWrapper::SetFavicons, backend_,
page_urls_to_save, icon_type, icon_url,
ExtractSkBitmapsToStore(image)));
}
void FaviconServiceImpl::CloneFaviconMappingsForPages(
const GURL& page_url_to_read,
const favicon_base::IconTypeSet& icon_types,
const base::flat_set<GURL>& page_urls_to_write) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
backend_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::CloneFaviconMappingsForPages,
backend_, page_url_to_read, icon_types,
page_urls_to_write));
}
base::CancelableTaskTracker::TaskId FaviconServiceImpl::GetFavicon(
const GURL& icon_url,
favicon_base::IconType icon_type,
int desired_size_in_dip,
favicon_base::FaviconResultsCallback callback,
base::CancelableTaskTracker* tracker) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return tracker->PostTaskAndReplyWithResult(
backend_task_runner_.get(), FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::GetFavicon, backend_, icon_url,
icon_type,
GetPixelSizesForFaviconScales(desired_size_in_dip)),
std::move(callback));
}
base::CancelableTaskTracker::TaskId
FaviconServiceImpl::UpdateFaviconMappingsAndFetch(
const base::flat_set<GURL>& page_urls,
const GURL& icon_url,
favicon_base::IconType icon_type,
int desired_size_in_dip,
favicon_base::FaviconResultsCallback callback,
base::CancelableTaskTracker* tracker) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return tracker->PostTaskAndReplyWithResult(
backend_task_runner_.get(), FROM_HERE,
base::BindOnce(&FaviconBackendWrapper::UpdateFaviconMappingsAndFetch,
backend_, page_urls, icon_url, icon_type,
GetPixelSizesForFaviconScales(desired_size_in_dip)),
std::move(callback));
}
void FaviconServiceImpl::DeleteFaviconMappings(
const base::flat_set<GURL>& page_urls,
favicon_base::IconType icon_type) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
backend_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&FaviconBackendWrapper::DeleteFaviconMappings,
backend_, page_urls, icon_type));
}
void FaviconServiceImpl::UnableToDownloadFavicon(const GURL& icon_url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
missing_favicon_urls_.insert(base::FastHash(icon_url.spec()));
if (observer_)
observer_->OnUnableToDownloadFavicon();
}
void FaviconServiceImpl::ClearUnableToDownloadFavicons() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
missing_favicon_urls_.clear();
}
bool FaviconServiceImpl::WasUnableToDownloadFavicon(
const GURL& icon_url) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
MissingFaviconUrlHash url_hash = base::FastHash(icon_url.spec());
return missing_favicon_urls_.find(url_hash) != missing_favicon_urls_.end();
}
// static
std::vector<int> FaviconServiceImpl::GetDesiredFaviconSizesInPixels() {
return GetPixelSizesForFaviconScales(GetDesiredFaviconSizeInDips());
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_service_impl.cc | C++ | unknown | 9,775 |
// 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_FAVICON_FAVICON_SERVICE_IMPL_H_
#define WEBLAYER_BROWSER_FAVICON_FAVICON_SERVICE_IMPL_H_
#include <unordered_set>
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/sequence_checker.h"
#include "base/task/sequenced_task_runner.h"
#include "components/favicon/core/core_favicon_service.h"
#include "components/favicon/core/large_favicon_provider.h"
namespace base {
class FilePath;
}
namespace weblayer {
class FaviconBackendWrapper;
class FaviconServiceImplObserver;
// FaviconServiceImpl provides the front end (ui side) access to the favicon
// database. Most functions are processed async on the backend task-runner.
class FaviconServiceImpl : public favicon::CoreFaviconService,
public favicon::LargeFaviconProvider {
public:
FaviconServiceImpl();
FaviconServiceImpl(const FaviconServiceImpl&) = delete;
FaviconServiceImpl& operator=(const FaviconServiceImpl&) = delete;
~FaviconServiceImpl() override;
void Init(const base::FilePath& db_path);
void set_observer(FaviconServiceImplObserver* observer) {
observer_ = observer;
}
// Deletes the database and recreates it, notifying |callback| when done.
void DeleteAndRecreateDatabase(base::OnceClosure callback);
// Requests the favicon image for a url (page). The returned image matches
// that returned from FaviconFetcher.
base::CancelableTaskTracker::TaskId GetFaviconForPageUrl(
const GURL& page_url,
base::OnceCallback<void(gfx::Image)> callback,
base::CancelableTaskTracker* tracker);
// favicon::CoreFaviconService:
base::CancelableTaskTracker::TaskId GetLargestRawFaviconForPageURL(
const GURL& page_url,
const std::vector<favicon_base::IconTypeSet>& icon_types,
int minimum_size_in_pixels,
favicon_base::FaviconRawBitmapCallback callback,
base::CancelableTaskTracker* tracker) override;
base::CancelableTaskTracker::TaskId GetFaviconForPageURL(
const GURL& page_url,
const favicon_base::IconTypeSet& icon_types,
int desired_size_in_dip,
favicon_base::FaviconResultsCallback callback,
base::CancelableTaskTracker* tracker) override;
void SetFaviconOutOfDateForPage(const GURL& page_url) override;
void SetFavicons(const base::flat_set<GURL>& page_urls,
const GURL& icon_url,
favicon_base::IconType icon_type,
const gfx::Image& image) override;
void CloneFaviconMappingsForPages(
const GURL& page_url_to_read,
const favicon_base::IconTypeSet& icon_types,
const base::flat_set<GURL>& page_urls_to_write) override;
base::CancelableTaskTracker::TaskId GetFavicon(
const GURL& icon_url,
favicon_base::IconType icon_type,
int desired_size_in_dip,
favicon_base::FaviconResultsCallback callback,
base::CancelableTaskTracker* tracker) override;
base::CancelableTaskTracker::TaskId UpdateFaviconMappingsAndFetch(
const base::flat_set<GURL>& page_urls,
const GURL& icon_url,
favicon_base::IconType icon_type,
int desired_size_in_dip,
favicon_base::FaviconResultsCallback callback,
base::CancelableTaskTracker* tracker) override;
void DeleteFaviconMappings(const base::flat_set<GURL>& page_urls,
favicon_base::IconType icon_type) override;
void UnableToDownloadFavicon(const GURL& icon_url) override;
void ClearUnableToDownloadFavicons() override;
bool WasUnableToDownloadFavicon(const GURL& icon_url) const override;
private:
using MissingFaviconUrlHash = size_t;
SEQUENCE_CHECKER(sequence_checker_);
// Returns the desired favicon sizes for the current platform.
static std::vector<int> GetDesiredFaviconSizesInPixels();
// The TaskRunner to which FaviconServiceBackend tasks are posted. Nullptr
// once Cleanup() is called.
scoped_refptr<base::SequencedTaskRunner> backend_task_runner_;
scoped_refptr<FaviconBackendWrapper> backend_;
// Hashes of the favicon urls that were unable to be downloaded.
std::unordered_set<MissingFaviconUrlHash> missing_favicon_urls_;
// This is only used in tests, where only a single observer is necessary.
raw_ptr<FaviconServiceImplObserver> observer_ = nullptr;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FAVICON_FAVICON_SERVICE_IMPL_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_service_impl.h | C++ | unknown | 4,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.
#include "weblayer/browser/favicon/favicon_service_impl_factory.h"
#include "base/files/file_path.h"
#include "base/no_destructor.h"
#include "components/favicon/content/large_favicon_provider_getter.h"
#include "components/favicon/core/core_favicon_service.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "content/public/browser/browser_context.h"
#include "weblayer/browser/favicon/favicon_service_impl.h"
namespace weblayer {
namespace {
favicon::LargeFaviconProvider* GetLargeFaviconProvider(
content::BrowserContext* browser_context) {
return FaviconServiceImplFactory::GetForBrowserContext(browser_context);
}
} // namespace
// static
FaviconServiceImpl* FaviconServiceImplFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
if (!browser_context->IsOffTheRecord()) {
return static_cast<FaviconServiceImpl*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true));
}
return nullptr;
}
// static
FaviconServiceImplFactory* FaviconServiceImplFactory::GetInstance() {
static base::NoDestructor<FaviconServiceImplFactory> factory;
return factory.get();
}
FaviconServiceImplFactory::FaviconServiceImplFactory()
: BrowserContextKeyedServiceFactory(
"FaviconServiceImpl",
BrowserContextDependencyManager::GetInstance()) {
favicon::SetLargeFaviconProviderGetter(
base::BindRepeating(&GetLargeFaviconProvider));
}
FaviconServiceImplFactory::~FaviconServiceImplFactory() = default;
KeyedService* FaviconServiceImplFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
DCHECK(!context->IsOffTheRecord());
std::unique_ptr<FaviconServiceImpl> service =
std::make_unique<FaviconServiceImpl>();
service->Init(context->GetPath().AppendASCII("Favicons"));
return service.release();
}
bool FaviconServiceImplFactory::ServiceIsNULLWhileTesting() const {
return true;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_service_impl_factory.cc | C++ | unknown | 2,123 |
// 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_FAVICON_FAVICON_SERVICE_IMPL_FACTORY_H_
#define WEBLAYER_BROWSER_FAVICON_FAVICON_SERVICE_IMPL_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace content {
class BrowserContext;
}
namespace weblayer {
class FaviconServiceImpl;
// BrowserContextKeyedServiceFactory for getting the FaviconServiceImpl.
class FaviconServiceImplFactory : public BrowserContextKeyedServiceFactory {
public:
FaviconServiceImplFactory(const FaviconServiceImplFactory&) = delete;
FaviconServiceImplFactory& operator=(const FaviconServiceImplFactory&) =
delete;
// Off the record profiles do not have a FaviconServiceImpl.
static FaviconServiceImpl* GetForBrowserContext(
content::BrowserContext* browser_context);
// Returns the FaviconServiceFactory singleton.
static FaviconServiceImplFactory* GetInstance();
private:
friend class base::NoDestructor<FaviconServiceImplFactory>;
FaviconServiceImplFactory();
~FaviconServiceImplFactory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
bool ServiceIsNULLWhileTesting() const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FAVICON_FAVICON_SERVICE_IMPL_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_service_impl_factory.h | C++ | unknown | 1,505 |
// 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_FAVICON_FAVICON_SERVICE_IMPL_OBSERVER_H_
#define WEBLAYER_BROWSER_FAVICON_FAVICON_SERVICE_IMPL_OBSERVER_H_
namespace weblayer {
class FaviconServiceImplObserver {
public:
// Called from FaviconServiceImpl::UnableToDownloadFavicon.
virtual void OnUnableToDownloadFavicon() {}
protected:
virtual ~FaviconServiceImplObserver() = default;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FAVICON_FAVICON_SERVICE_IMPL_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_service_impl_observer.h | C++ | unknown | 614 |
// 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/favicon/favicon_tab_helper.h"
#include "components/favicon/content/content_favicon_driver.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "weblayer/browser/favicon/favicon_service_impl.h"
#include "weblayer/browser/favicon/favicon_service_impl_factory.h"
#include "weblayer/public/favicon_fetcher_delegate.h"
namespace weblayer {
namespace {
bool IsSquareImage(const gfx::Image& image) {
return !image.IsEmpty() && image.Width() == image.Height();
}
// Returns true if |image_a| is better than |image_b|. A value of false means
// |image_a| is not better than |image_b|. Either image may be empty, if both
// are empty false is returned.
bool IsImageBetterThan(const gfx::Image& image_a, const gfx::Image& image_b) {
// Any image is better than an empty image.
if (!image_a.IsEmpty() && image_b.IsEmpty())
return true;
// Prefer square favicons as they will scale much better.
if (IsSquareImage(image_a) && !IsSquareImage(image_b))
return true;
return image_a.Width() > image_b.Width();
}
} // namespace
FaviconTabHelper::ObserverSubscription::ObserverSubscription(
FaviconTabHelper* helper,
FaviconFetcherDelegate* delegate)
: helper_(helper), delegate_(delegate) {
helper_->AddDelegate(delegate_);
}
FaviconTabHelper::ObserverSubscription::~ObserverSubscription() {
helper_->RemoveDelegate(delegate_);
}
FaviconTabHelper::~FaviconTabHelper() {
// All of the ObserverSubscriptions should have been destroyed before this.
DCHECK_EQ(0, observer_count_);
}
std::unique_ptr<FaviconTabHelper::ObserverSubscription>
FaviconTabHelper::RegisterFaviconFetcherDelegate(
FaviconFetcherDelegate* delegate) {
// WrapUnique as constructor is private.
return base::WrapUnique(new ObserverSubscription(this, delegate));
}
FaviconTabHelper::FaviconTabHelper(content::WebContents* contents)
: content::WebContentsUserData<FaviconTabHelper>(*contents),
WebContentsObserver(contents) {}
void FaviconTabHelper::AddDelegate(FaviconFetcherDelegate* delegate) {
delegates_.AddObserver(delegate);
if (++observer_count_ == 1) {
FaviconServiceImpl* favicon_service =
FaviconServiceImplFactory::GetForBrowserContext(
web_contents()->GetBrowserContext());
favicon::ContentFaviconDriver::CreateForWebContents(web_contents(),
favicon_service);
favicon::ContentFaviconDriver::FromWebContents(web_contents())
->AddObserver(this);
}
}
void FaviconTabHelper::RemoveDelegate(FaviconFetcherDelegate* delegate) {
delegates_.RemoveObserver(delegate);
--observer_count_;
DCHECK_GE(observer_count_, 0);
if (observer_count_ == 0) {
favicon::ContentFaviconDriver::FromWebContents(web_contents())
->RemoveObserver(this);
// ContentFaviconDriver downloads images, if there are no observers there
// is no need to keep it around. This triggers deleting it.
web_contents()->SetUserData(favicon::ContentFaviconDriver::UserDataKey(),
nullptr);
favicon_ = gfx::Image();
}
}
void FaviconTabHelper::OnFaviconUpdated(
favicon::FaviconDriver* favicon_driver,
NotificationIconType notification_icon_type,
const GURL& icon_url,
bool icon_url_changed,
const gfx::Image& image) {
if (!IsImageBetterThan(image, favicon_))
return;
favicon_ = image;
for (FaviconFetcherDelegate& delegate : delegates_)
delegate.OnFaviconChanged(favicon_);
}
void FaviconTabHelper::PrimaryPageChanged(content::Page& page) {
if (page.GetMainDocument().IsErrorDocument() || favicon_.IsEmpty()) {
return;
}
favicon_ = gfx::Image();
for (FaviconFetcherDelegate& delegate : delegates_)
delegate.OnFaviconChanged(favicon_);
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(FaviconTabHelper);
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_tab_helper.cc | C++ | unknown | 4,057 |
// 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_FAVICON_FAVICON_TAB_HELPER_H_
#define WEBLAYER_BROWSER_FAVICON_FAVICON_TAB_HELPER_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "components/favicon/core/favicon_driver_observer.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "ui/gfx/image/image.h"
namespace weblayer {
class FaviconFetcherDelegate;
// FaviconTabHelper is responsible for creating favicon::ContentFaviconDriver
// when necessary. FaviconTabHelper is used by FaviconFetcherImpl and notifies
// FaviconFetcherDelegate when the favicon changes.
class FaviconTabHelper : public content::WebContentsUserData<FaviconTabHelper>,
public content::WebContentsObserver,
public favicon::FaviconDriverObserver {
public:
// Used to track calls to RegisterFaviconFetcherDelegate(). When destroyed
// the FaviconFetcherDelegate is removed.
class ObserverSubscription {
public:
ObserverSubscription(const ObserverSubscription&) = delete;
ObserverSubscription& operator=(const ObserverSubscription&) = delete;
~ObserverSubscription();
private:
friend class FaviconTabHelper;
ObserverSubscription(FaviconTabHelper* helper,
FaviconFetcherDelegate* delegate);
raw_ptr<FaviconTabHelper> helper_;
raw_ptr<FaviconFetcherDelegate> delegate_;
};
FaviconTabHelper(const FaviconTabHelper&) = delete;
FaviconTabHelper& operator=(const FaviconTabHelper&) = delete;
~FaviconTabHelper() override;
// Called when FaviconFetcherImpl is created. This ensures the necessary
// wiring is in place and notifies |delegate| when the favicon changes.
std::unique_ptr<ObserverSubscription> RegisterFaviconFetcherDelegate(
FaviconFetcherDelegate* delegate);
// Returns the favicon for the current navigation.
const gfx::Image& favicon() const { return favicon_; }
private:
friend class content::WebContentsUserData<FaviconTabHelper>;
explicit FaviconTabHelper(content::WebContents* contents);
void AddDelegate(FaviconFetcherDelegate* delegate);
void RemoveDelegate(FaviconFetcherDelegate* delegate);
// favicon::FaviconDriverObserver:
void OnFaviconUpdated(favicon::FaviconDriver* favicon_driver,
NotificationIconType notification_icon_type,
const GURL& icon_url,
bool icon_url_changed,
const gfx::Image& image) override;
// content::WebContentsObserver:
void PrimaryPageChanged(content::Page& page) override;
raw_ptr<content::WebContents> web_contents_;
// Number of observers attached.
int observer_count_ = 0;
base::ObserverList<FaviconFetcherDelegate> delegates_;
gfx::Image favicon_;
WEB_CONTENTS_USER_DATA_KEY_DECL();
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FAVICON_FAVICON_TAB_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/favicon_tab_helper.h | C++ | unknown | 3,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.
#include "weblayer/browser/favicon/test_favicon_fetcher_delegate.h"
#include "base/run_loop.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace weblayer {
TestFaviconFetcherDelegate::TestFaviconFetcherDelegate() = default;
TestFaviconFetcherDelegate::~TestFaviconFetcherDelegate() = default;
void TestFaviconFetcherDelegate::WaitForFavicon() {
ASSERT_EQ(nullptr, run_loop_.get());
waiting_for_nonempty_image_ = false;
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
run_loop_.reset();
}
void TestFaviconFetcherDelegate::WaitForNonemptyFavicon() {
if (!last_image_.IsEmpty())
return;
run_loop_ = std::make_unique<base::RunLoop>();
waiting_for_nonempty_image_ = true;
run_loop_->Run();
run_loop_.reset();
}
void TestFaviconFetcherDelegate::ClearLastImage() {
last_image_ = gfx::Image();
on_favicon_changed_call_count_ = 0;
}
void TestFaviconFetcherDelegate::OnFaviconChanged(const gfx::Image& image) {
last_image_ = image;
++on_favicon_changed_call_count_;
if (run_loop_ && (!waiting_for_nonempty_image_ || !image.IsEmpty()))
run_loop_->Quit();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/test_favicon_fetcher_delegate.cc | C++ | unknown | 1,287 |
// 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_FAVICON_TEST_FAVICON_FETCHER_DELEGATE_H_
#define WEBLAYER_BROWSER_FAVICON_TEST_FAVICON_FETCHER_DELEGATE_H_
#include <memory>
#include "ui/gfx/image/image.h"
#include "weblayer/public/favicon_fetcher_delegate.h"
namespace base {
class RunLoop;
}
namespace weblayer {
// Records calls to OnFaviconChanged().
class TestFaviconFetcherDelegate : public FaviconFetcherDelegate {
public:
TestFaviconFetcherDelegate();
TestFaviconFetcherDelegate(const TestFaviconFetcherDelegate&) = delete;
TestFaviconFetcherDelegate& operator=(const TestFaviconFetcherDelegate&) =
delete;
~TestFaviconFetcherDelegate() override;
// Waits for OnFaviconChanged() to be called.
void WaitForFavicon();
// Waits for a non-empty favicon. This returns immediately if a non-empty
// image was supplied to OnFaviconChanged() and ClearLastImage() hasn't been
// called.
void WaitForNonemptyFavicon();
void ClearLastImage();
const gfx::Image& last_image() const { return last_image_; }
int on_favicon_changed_call_count() const {
return on_favicon_changed_call_count_;
}
// FaviconFetcherDelegate:
void OnFaviconChanged(const gfx::Image& image) override;
private:
std::unique_ptr<base::RunLoop> run_loop_;
gfx::Image last_image_;
bool waiting_for_nonempty_image_ = false;
int on_favicon_changed_call_count_ = 0;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FAVICON_TEST_FAVICON_FETCHER_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/favicon/test_favicon_fetcher_delegate.h | C++ | unknown | 1,609 |
// 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/feature_list_creator.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "build/build_config.h"
#include "components/metrics/metrics_state_manager.h"
#include "components/prefs/pref_service.h"
#include "components/variations/service/variations_service.h"
#include "components/variations/variations_crash_keys.h"
#include "components/variations/variations_switches.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/common/content_switch_dependent_feature_overrides.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "weblayer/browser/system_network_context_manager.h"
#include "weblayer/browser/weblayer_variations_service_client.h"
#if BUILDFLAG(IS_ANDROID)
#include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
#endif
#if BUILDFLAG(IS_ANDROID)
namespace switches {
const char kDisableBackgroundNetworking[] = "disable-background-networking";
} // namespace switches
#endif
namespace weblayer {
namespace {
FeatureListCreator* feature_list_creator_instance = nullptr;
} // namespace
FeatureListCreator::FeatureListCreator(PrefService* local_state)
: local_state_(local_state) {
DCHECK(local_state_);
DCHECK(!feature_list_creator_instance);
feature_list_creator_instance = this;
}
FeatureListCreator::~FeatureListCreator() {
feature_list_creator_instance = nullptr;
}
// static
FeatureListCreator* FeatureListCreator::GetInstance() {
DCHECK(feature_list_creator_instance);
return feature_list_creator_instance;
}
void FeatureListCreator::SetSystemNetworkContextManager(
SystemNetworkContextManager* system_network_context_manager) {
system_network_context_manager_ = system_network_context_manager;
}
void FeatureListCreator::CreateFeatureListAndFieldTrials() {
#if BUILDFLAG(IS_ANDROID)
WebLayerMetricsServiceClient::GetInstance()->Initialize(local_state_);
#endif
SetUpFieldTrials();
}
void FeatureListCreator::PerformPreMainMessageLoopStartup() {
#if BUILDFLAG(IS_ANDROID)
// It is expected this is called after SetUpFieldTrials().
DCHECK(variations_service_);
variations_service_->PerformPreMainMessageLoopStartup();
#endif
}
void FeatureListCreator::OnBrowserFragmentStarted() {
if (has_browser_fragment_started_)
return;
has_browser_fragment_started_ = true;
// It is expected this is called after SetUpFieldTrials().
DCHECK(variations_service_);
// This function is called any time a BrowserFragment is started.
// OnAppEnterForeground() really need only be called once, and because our
// notion of a fragment doesn't really map to the Application as a whole,
// call this function once.
variations_service_->OnAppEnterForeground();
}
void FeatureListCreator::SetUpFieldTrials() {
#if BUILDFLAG(IS_ANDROID)
// The FieldTrialList should have been instantiated in
// AndroidMetricsServiceClient::Initialize().
DCHECK(base::FieldTrialList::GetInstance());
DCHECK(system_network_context_manager_);
auto* metrics_client = WebLayerMetricsServiceClient::GetInstance();
variations_service_ = variations::VariationsService::Create(
std::make_unique<WebLayerVariationsServiceClient>(
system_network_context_manager_),
local_state_, metrics_client->metrics_state_manager(),
switches::kDisableBackgroundNetworking, variations::UIStringOverrider(),
base::BindOnce(&content::GetNetworkConnectionTracker));
variations_service_->OverridePlatform(
variations::Study::PLATFORM_ANDROID_WEBLAYER, "android_weblayer");
std::vector<std::string> variation_ids;
auto feature_list = std::make_unique<base::FeatureList>();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
variations_service_->SetUpFieldTrials(
variation_ids,
command_line->GetSwitchValueASCII(
variations::switches::kForceVariationIds),
content::GetSwitchDependentFeatureOverrides(*command_line),
std::move(feature_list), &weblayer_field_trials_);
variations::InitCrashKeys();
#else
// TODO(weblayer-dev): Support variations on desktop.
#endif
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/feature_list_creator.cc | C++ | unknown | 4,317 |
// 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_FEATURE_LIST_CREATOR_H_
#define WEBLAYER_BROWSER_FEATURE_LIST_CREATOR_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "weblayer/browser/weblayer_field_trials.h"
class PrefService;
namespace variations {
class VariationsService;
}
namespace weblayer {
class SystemNetworkContextManager;
// Used by WebLayer to set up field trials based on the stored variations
// seed data. Once created this object must exist for the lifetime of the
// process as it contains the FieldTrialList that can be queried for the state
// of experiments.
class FeatureListCreator {
public:
explicit FeatureListCreator(PrefService* local_state);
FeatureListCreator(const FeatureListCreator&) = delete;
FeatureListCreator& operator=(const FeatureListCreator&) = delete;
~FeatureListCreator();
// Return the single instance of FeatureListCreator. This does *not* trigger
// creation.
static FeatureListCreator* GetInstance();
void SetSystemNetworkContextManager(
SystemNetworkContextManager* system_network_context_manager);
// Must be called after SetSharedURLLoaderFactory.
void CreateFeatureListAndFieldTrials();
// Called from content::BrowserMainParts::PreMainMessageLoopRun() to perform
// initialization necessary prior to running the main message loop.
void PerformPreMainMessageLoopStartup();
// Calls through to the VariationService.
void OnBrowserFragmentStarted();
variations::VariationsService* variations_service() const {
return variations_service_.get();
}
private:
void SetUpFieldTrials();
// Owned by BrowserProcess.
raw_ptr<PrefService> local_state_;
raw_ptr<SystemNetworkContextManager>
system_network_context_manager_; // NOT OWNED.
std::unique_ptr<variations::VariationsService> variations_service_;
WebLayerFieldTrials weblayer_field_trials_;
// Set to true the first time OnBrowserFragmentStarted() is called.
bool has_browser_fragment_started_ = false;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FEATURE_LIST_CREATOR_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/feature_list_creator.h | C++ | unknown | 2,205 |
// 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/file_select_helper.h"
#include <string>
#include "build/build_config.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "ui/shell_dialogs/select_file_policy.h"
#include "ui/shell_dialogs/selected_file_info.h"
#if BUILDFLAG(IS_ANDROID)
#include "ui/android/view_android.h"
#else
#include "ui/aura/window.h"
#endif
namespace weblayer {
using blink::mojom::FileChooserFileInfo;
using blink::mojom::FileChooserFileInfoPtr;
using blink::mojom::FileChooserParams;
using blink::mojom::FileChooserParamsPtr;
// static
void FileSelectHelper::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const FileChooserParams& params) {
// TODO: Should we handle text/json+contacts accept type?
// FileSelectHelper will keep itself alive until it sends the result
// message.
scoped_refptr<FileSelectHelper> file_select_helper(new FileSelectHelper());
file_select_helper->RunFileChooser(render_frame_host, std::move(listener),
params.Clone());
}
FileSelectHelper::FileSelectHelper() = default;
FileSelectHelper::~FileSelectHelper() {
// There may be pending file dialogs, we need to tell them that we've gone
// away so they don't try and call back to us.
if (select_file_dialog_)
select_file_dialog_->ListenerDestroyed();
}
void FileSelectHelper::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
FileChooserParamsPtr params) {
DCHECK(!web_contents_);
DCHECK(listener);
DCHECK(!listener_);
DCHECK(!select_file_dialog_);
listener_ = std::move(listener);
web_contents_ = content::WebContents::FromRenderFrameHost(render_frame_host)
->GetWeakPtr();
select_file_dialog_ = ui::SelectFileDialog::Create(this, nullptr);
dialog_mode_ = params->mode;
switch (params->mode) {
case FileChooserParams::Mode::kOpen:
dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_FILE;
break;
case FileChooserParams::Mode::kOpenMultiple:
dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE;
break;
case FileChooserParams::Mode::kUploadFolder:
// For now we don't support inputs with webkitdirectory in weblayer.
dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE;
break;
case FileChooserParams::Mode::kSave:
dialog_type_ = ui::SelectFileDialog::SELECT_SAVEAS_FILE;
break;
default:
// Prevent warning.
dialog_type_ = ui::SelectFileDialog::SELECT_OPEN_FILE;
NOTREACHED();
}
gfx::NativeWindow owning_window;
#if BUILDFLAG(IS_ANDROID)
owning_window = web_contents_->GetNativeView()->GetWindowAndroid();
#else
owning_window = web_contents_->GetNativeView()->GetToplevelWindow();
#endif
#if BUILDFLAG(IS_ANDROID)
// Android needs the original MIME types and an additional capture value.
std::pair<std::vector<std::u16string>, bool> accept_types =
std::make_pair(params->accept_types, params->use_media_capture);
#endif
// Many of these params are not used in the Android SelectFileDialog
// implementation, so we can safely pass empty values.
select_file_dialog_->SelectFile(dialog_type_, std::u16string(),
base::FilePath(), nullptr, 0,
base::FilePath::StringType(), owning_window,
#if BUILDFLAG(IS_ANDROID)
&accept_types);
#else
nullptr);
#endif
// Because this class returns notifications to the RenderViewHost, it is
// difficult for callers to know how long to keep a reference to this
// instance. We AddRef() here to keep the instance alive after we return
// to the caller, until the last callback is received from the file dialog.
// At that point, we must call RunFileChooserEnd().
AddRef();
}
void FileSelectHelper::RunFileChooserEnd() {
if (listener_)
listener_->FileSelectionCanceled();
select_file_dialog_->ListenerDestroyed();
select_file_dialog_.reset();
Release();
}
void FileSelectHelper::FileSelected(const base::FilePath& path,
int index,
void* params) {
FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params);
}
void FileSelectHelper::FileSelectedWithExtraInfo(
const ui::SelectedFileInfo& file,
int index,
void* params) {
ConvertToFileChooserFileInfoList({file});
}
void FileSelectHelper::MultiFilesSelected(
const std::vector<base::FilePath>& files,
void* params) {
std::vector<ui::SelectedFileInfo> selected_files =
ui::FilePathListToSelectedFileInfoList(files);
MultiFilesSelectedWithExtraInfo(selected_files, params);
}
void FileSelectHelper::MultiFilesSelectedWithExtraInfo(
const std::vector<ui::SelectedFileInfo>& files,
void* params) {
ConvertToFileChooserFileInfoList(files);
}
void FileSelectHelper::FileSelectionCanceled(void* params) {
RunFileChooserEnd();
}
void FileSelectHelper::ConvertToFileChooserFileInfoList(
const std::vector<ui::SelectedFileInfo>& files) {
if (!web_contents_) {
RunFileChooserEnd();
return;
}
std::vector<FileChooserFileInfoPtr> chooser_files;
for (const auto& file : files) {
chooser_files.push_back(
FileChooserFileInfo::NewNativeFile(blink::mojom::NativeFileInfo::New(
file.local_path,
base::FilePath(file.display_name).AsUTF16Unsafe())));
}
listener_->FileSelected(std::move(chooser_files), base::FilePath(),
dialog_mode_);
listener_ = nullptr;
// No members should be accessed from here on.
RunFileChooserEnd();
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/file_select_helper.cc | C++ | unknown | 5,987 |
// 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_FILE_SELECT_HELPER_H_
#define WEBLAYER_BROWSER_FILE_SELECT_HELPER_H_
#include <memory>
#include <vector>
#include "base/memory/weak_ptr.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/file_select_listener.h"
#include "ui/shell_dialogs/select_file_dialog.h"
namespace content {
class FileSelectListener;
class RenderFrameHost;
class WebContents;
} // namespace content
namespace ui {
struct SelectedFileInfo;
}
namespace weblayer {
// This class handles file-selection requests coming from renderer processes.
// It implements both the initialisation and listener functions for
// file-selection dialogs.
//
// Since FileSelectHelper listens to observations of a widget, it needs to live
// on and be destroyed on the UI thread. References to FileSelectHelper may be
// passed on to other threads.
class FileSelectHelper : public base::RefCountedThreadSafe<
FileSelectHelper,
content::BrowserThread::DeleteOnUIThread>,
public ui::SelectFileDialog::Listener {
public:
FileSelectHelper(const FileSelectHelper&) = delete;
FileSelectHelper& operator=(const FileSelectHelper&) = delete;
// Show the file chooser dialog.
static void RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params);
private:
friend class base::RefCountedThreadSafe<FileSelectHelper>;
friend class base::DeleteHelper<FileSelectHelper>;
friend struct content::BrowserThread::DeleteOnThread<
content::BrowserThread::UI>;
FileSelectHelper();
~FileSelectHelper() override;
void RunFileChooser(content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
blink::mojom::FileChooserParamsPtr params);
// Cleans up and releases this instance. This must be called after the last
// callback is received from the file chooser dialog.
void RunFileChooserEnd();
// SelectFileDialog::Listener overrides.
void FileSelected(const base::FilePath& path,
int index,
void* params) override;
void FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file,
int index,
void* params) override;
void MultiFilesSelected(const std::vector<base::FilePath>& files,
void* params) override;
void MultiFilesSelectedWithExtraInfo(
const std::vector<ui::SelectedFileInfo>& files,
void* params) override;
void FileSelectionCanceled(void* params) override;
// This method is called after the user has chosen the file(s) in the UI in
// order to process and filter the list before returning the final result to
// the caller.
void ConvertToFileChooserFileInfoList(
const std::vector<ui::SelectedFileInfo>& files);
// A weak pointer to the WebContents of the RenderFrameHost, for life checks.
base::WeakPtr<content::WebContents> web_contents_;
// |listener_| receives the result of the FileSelectHelper.
scoped_refptr<content::FileSelectListener> listener_;
// Dialog box used for choosing files to upload from file form fields.
scoped_refptr<ui::SelectFileDialog> select_file_dialog_;
// The type of file dialog last shown.
ui::SelectFileDialog::Type dialog_type_ =
ui::SelectFileDialog::SELECT_OPEN_FILE;
// The mode of file dialog last shown.
blink::mojom::FileChooserParams::Mode dialog_mode_ =
blink::mojom::FileChooserParams::Mode::kOpen;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FILE_SELECT_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/file_select_helper.h | C++ | unknown | 3,905 |
// 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/test/weblayer_browser_test.h"
#include "base/functional/callback.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/browser.h"
#include "weblayer/public/fullscreen_delegate.h"
#include "weblayer/shell/browser/shell.h"
#include "weblayer/test/weblayer_browser_test_utils.h"
namespace weblayer {
using FullscreenBrowserTest = WebLayerBrowserTest;
class FullscreenDelegateImpl : public FullscreenDelegate {
public:
bool got_enter() const { return got_enter_; }
bool got_exit() const { return got_exit_; }
void ResetState() { got_enter_ = got_exit_ = false; }
// FullscreenDelegate:
void EnterFullscreen(base::OnceClosure exit_closure) override {
got_enter_ = true;
}
void ExitFullscreen() override { got_exit_ = true; }
private:
bool got_enter_ = false;
bool got_exit_ = false;
};
IN_PROC_BROWSER_TEST_F(FullscreenBrowserTest, EnterFromBackgroundTab) {
EXPECT_TRUE(embedded_test_server()->Start());
TabImpl* tab1 = static_cast<TabImpl*>(shell()->tab());
Browser* browser = tab1->GetBrowser();
TabImpl* tab2 = static_cast<TabImpl*>(browser->CreateTab());
EXPECT_NE(tab2, browser->GetActiveTab());
FullscreenDelegateImpl fullscreen_delegate;
tab2->SetFullscreenDelegate(&fullscreen_delegate);
// As `tab2` is in the background, the delegate should not be notified.
static_cast<content::WebContentsDelegate*>(tab2)->EnterFullscreenModeForTab(
nullptr, blink::mojom::FullscreenOptions());
EXPECT_TRUE(static_cast<content::WebContentsDelegate*>(tab2)
->IsFullscreenForTabOrPending(nullptr));
EXPECT_FALSE(fullscreen_delegate.got_enter());
// Making the tab active should trigger the going fullscreen.
browser->SetActiveTab(tab2);
EXPECT_TRUE(static_cast<content::WebContentsDelegate*>(tab2)
->IsFullscreenForTabOrPending(nullptr));
EXPECT_TRUE(fullscreen_delegate.got_enter());
tab2->SetFullscreenDelegate(nullptr);
}
IN_PROC_BROWSER_TEST_F(FullscreenBrowserTest, NoExitForBackgroundTab) {
EXPECT_TRUE(embedded_test_server()->Start());
Browser* browser = shell()->tab()->GetBrowser();
TabImpl* tab = static_cast<TabImpl*>(browser->CreateTab());
EXPECT_NE(tab, browser->GetActiveTab());
FullscreenDelegateImpl fullscreen_delegate;
tab->SetFullscreenDelegate(&fullscreen_delegate);
// As `tab` is in the background, the delegate should not be notified.
static_cast<content::WebContentsDelegate*>(tab)->EnterFullscreenModeForTab(
nullptr, blink::mojom::FullscreenOptions());
EXPECT_TRUE(static_cast<content::WebContentsDelegate*>(tab)
->IsFullscreenForTabOrPending(nullptr));
EXPECT_FALSE(fullscreen_delegate.got_enter());
EXPECT_TRUE(static_cast<content::WebContentsDelegate*>(tab)
->IsFullscreenForTabOrPending(nullptr));
EXPECT_FALSE(fullscreen_delegate.got_enter());
EXPECT_FALSE(fullscreen_delegate.got_exit());
fullscreen_delegate.ResetState();
// Simulate exiting. As the delegate wasn't told about the enter, it should
// not be told about the exit.
static_cast<content::WebContentsDelegate*>(tab)->ExitFullscreenModeForTab(
nullptr);
EXPECT_FALSE(static_cast<content::WebContentsDelegate*>(tab)
->IsFullscreenForTabOrPending(nullptr));
EXPECT_FALSE(fullscreen_delegate.got_enter());
EXPECT_FALSE(fullscreen_delegate.got_exit());
tab->SetFullscreenDelegate(nullptr);
}
IN_PROC_BROWSER_TEST_F(FullscreenBrowserTest, DelegateNotCalledMoreThanOnce) {
EXPECT_TRUE(embedded_test_server()->Start());
// The tab needs to be made active as fullscreen requests for inactive tabs
// are ignored.
TabImpl* tab = static_cast<TabImpl*>(shell()->tab());
tab->GetBrowser()->SetActiveTab(tab);
FullscreenDelegateImpl fullscreen_delegate;
tab->SetFullscreenDelegate(&fullscreen_delegate);
static_cast<content::WebContentsDelegate*>(tab)->EnterFullscreenModeForTab(
nullptr, blink::mojom::FullscreenOptions());
EXPECT_TRUE(static_cast<content::WebContentsDelegate*>(tab)
->IsFullscreenForTabOrPending(nullptr));
EXPECT_TRUE(fullscreen_delegate.got_enter());
EXPECT_FALSE(fullscreen_delegate.got_exit());
fullscreen_delegate.ResetState();
// Simulate another enter. As the tab is already fullscreen the delegate
// should not be notified again.
static_cast<content::WebContentsDelegate*>(tab)->EnterFullscreenModeForTab(
nullptr, blink::mojom::FullscreenOptions());
EXPECT_TRUE(static_cast<content::WebContentsDelegate*>(tab)
->IsFullscreenForTabOrPending(nullptr));
EXPECT_FALSE(fullscreen_delegate.got_enter());
EXPECT_FALSE(fullscreen_delegate.got_exit());
tab->SetFullscreenDelegate(nullptr);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/fullscreen_browsertest.cc | C++ | unknown | 4,965 |
// 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/fullscreen_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/FullscreenCallbackProxy_jni.h"
#include "weblayer/browser/tab_impl.h"
using base::android::AttachCurrentThread;
using base::android::ConvertUTF8ToJavaString;
using base::android::ScopedJavaLocalRef;
namespace weblayer {
FullscreenCallbackProxy::FullscreenCallbackProxy(JNIEnv* env,
jobject obj,
Tab* tab)
: tab_(tab), java_delegate_(env, obj) {
tab_->SetFullscreenDelegate(this);
}
FullscreenCallbackProxy::~FullscreenCallbackProxy() {
tab_->SetFullscreenDelegate(nullptr);
}
void FullscreenCallbackProxy::EnterFullscreen(base::OnceClosure exit_closure) {
exit_fullscreen_closure_ = std::move(exit_closure);
TRACE_EVENT0("weblayer", "Java_FullscreenCallbackProxy_enterFullscreen");
Java_FullscreenCallbackProxy_enterFullscreen(AttachCurrentThread(),
java_delegate_);
}
void FullscreenCallbackProxy::ExitFullscreen() {
TRACE_EVENT0("weblayer", "Java_FullscreenCallbackProxy_exitFullscreen");
// If the web contents initiated the fullscreen exit, the closure will still
// be valid, so clean it up now.
exit_fullscreen_closure_.Reset();
Java_FullscreenCallbackProxy_exitFullscreen(AttachCurrentThread(),
java_delegate_);
}
void FullscreenCallbackProxy::DoExitFullscreen(JNIEnv* env) {
if (exit_fullscreen_closure_)
std::move(exit_fullscreen_closure_).Run();
}
static jlong JNI_FullscreenCallbackProxy_CreateFullscreenCallbackProxy(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& proxy,
jlong tab) {
return reinterpret_cast<jlong>(
new FullscreenCallbackProxy(env, proxy, reinterpret_cast<TabImpl*>(tab)));
}
static void JNI_FullscreenCallbackProxy_DeleteFullscreenCallbackProxy(
JNIEnv* env,
jlong proxy) {
delete reinterpret_cast<FullscreenCallbackProxy*>(proxy);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/fullscreen_callback_proxy.cc | C++ | unknown | 2,299 |
// 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_FULLSCREEN_CALLBACK_PROXY_H_
#define WEBLAYER_BROWSER_FULLSCREEN_CALLBACK_PROXY_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "weblayer/public/fullscreen_delegate.h"
namespace weblayer {
class Tab;
// FullscreenCallbackProxy forwards all FullscreenDelegate functions to the
// Java side. There is at most one FullscreenCallbackProxy per
// Tab.
class FullscreenCallbackProxy : public FullscreenDelegate {
public:
FullscreenCallbackProxy(JNIEnv* env, jobject obj, Tab* tab);
FullscreenCallbackProxy(const FullscreenCallbackProxy&) = delete;
FullscreenCallbackProxy& operator=(const FullscreenCallbackProxy&) = delete;
~FullscreenCallbackProxy() override;
// FullscreenDelegate:
void EnterFullscreen(base::OnceClosure exit_closure) override;
void ExitFullscreen() override;
// Called from the Java side to exit fullscreen.
void DoExitFullscreen(JNIEnv* env);
private:
raw_ptr<Tab> tab_;
base::android::ScopedJavaGlobalRef<jobject> java_delegate_;
base::OnceClosure exit_fullscreen_closure_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_FULLSCREEN_CALLBACK_PROXY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/fullscreen_callback_proxy.h | C++ | unknown | 1,377 |
// 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/google_account_access_token_fetcher_proxy.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "weblayer/browser/java/jni/GoogleAccountAccessTokenFetcherProxy_jni.h"
#include "weblayer/browser/profile_impl.h"
namespace weblayer {
GoogleAccountAccessTokenFetcherProxy::GoogleAccountAccessTokenFetcherProxy(
JNIEnv* env,
jobject obj,
Profile* profile)
: java_delegate_(env, obj), profile_(profile) {
profile_->SetGoogleAccountAccessTokenFetchDelegate(this);
}
GoogleAccountAccessTokenFetcherProxy::~GoogleAccountAccessTokenFetcherProxy() {
profile_->SetGoogleAccountAccessTokenFetchDelegate(nullptr);
}
void GoogleAccountAccessTokenFetcherProxy::FetchAccessToken(
const std::set<std::string>& scopes,
OnTokenFetchedCallback callback) {
JNIEnv* env = base::android::AttachCurrentThread();
std::vector<std::string> scopes_as_vector(scopes.begin(), scopes.end());
// Copy |callback| on the heap to pass the pointer through JNI. This callback
// will be deleted when it's run.
jlong callback_id =
reinterpret_cast<jlong>(new OnTokenFetchedCallback(std::move(callback)));
Java_GoogleAccountAccessTokenFetcherProxy_fetchAccessToken(
env, java_delegate_,
base::android::ToJavaArrayOfStrings(env, scopes_as_vector),
reinterpret_cast<jlong>(callback_id));
}
void GoogleAccountAccessTokenFetcherProxy::OnAccessTokenIdentifiedAsInvalid(
const std::set<std::string>& scopes,
const std::string& token) {
JNIEnv* env = base::android::AttachCurrentThread();
std::vector<std::string> scopes_as_vector(scopes.begin(), scopes.end());
Java_GoogleAccountAccessTokenFetcherProxy_onAccessTokenIdentifiedAsInvalid(
env, java_delegate_,
base::android::ToJavaArrayOfStrings(env, scopes_as_vector),
base::android::ConvertUTF8ToJavaString(env, token));
}
static jlong
JNI_GoogleAccountAccessTokenFetcherProxy_CreateGoogleAccountAccessTokenFetcherProxy(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& proxy,
jlong profile) {
return reinterpret_cast<jlong>(new GoogleAccountAccessTokenFetcherProxy(
env, proxy, reinterpret_cast<ProfileImpl*>(profile)));
}
static void
JNI_GoogleAccountAccessTokenFetcherProxy_DeleteGoogleAccountAccessTokenFetcherProxy(
JNIEnv* env,
jlong proxy) {
delete reinterpret_cast<GoogleAccountAccessTokenFetcherProxy*>(proxy);
}
static void JNI_GoogleAccountAccessTokenFetcherProxy_RunOnTokenFetchedCallback(
JNIEnv* env,
jlong callback_id,
const base::android::JavaParamRef<jstring>& token) {
std::unique_ptr<OnTokenFetchedCallback> cb(
reinterpret_cast<OnTokenFetchedCallback*>(callback_id));
std::move(*cb).Run(base::android::ConvertJavaStringToUTF8(env, token));
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/google_account_access_token_fetcher_proxy.cc | C++ | unknown | 2,962 |
// 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_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCHER_PROXY_H_
#define WEBLAYER_BROWSER_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCHER_PROXY_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "weblayer/public/google_account_access_token_fetch_delegate.h"
namespace weblayer {
class Profile;
// Forwards GoogleAccountAccessTokenFetchDelegate calls to the java-side
// GoogleAccountAccessTokenFetcherProxy.
class GoogleAccountAccessTokenFetcherProxy
: public GoogleAccountAccessTokenFetchDelegate {
public:
GoogleAccountAccessTokenFetcherProxy(JNIEnv* env,
jobject obj,
Profile* profile);
~GoogleAccountAccessTokenFetcherProxy() override;
GoogleAccountAccessTokenFetcherProxy(
const GoogleAccountAccessTokenFetcherProxy&) = delete;
GoogleAccountAccessTokenFetcherProxy& operator=(
const GoogleAccountAccessTokenFetcherProxy&) = delete;
// GoogleAccountAccessTokenFetchDelegate:
void FetchAccessToken(const std::set<std::string>& scopes,
OnTokenFetchedCallback callback) override;
void OnAccessTokenIdentifiedAsInvalid(const std::set<std::string>& scopes,
const std::string& token) override;
private:
base::android::ScopedJavaGlobalRef<jobject> java_delegate_;
raw_ptr<Profile> profile_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_GOOGLE_ACCOUNT_ACCESS_TOKEN_FETCHER_PROXY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/google_account_access_token_fetcher_proxy.h | C++ | unknown | 1,705 |
// 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/strings/escape.h"
#include "base/strings/strcat.h"
#include "components/signin/core/browser/signin_header_helper.h"
#include "google_apis/gaia/gaia_switches.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/url_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "weblayer/browser/browser_impl.h"
#include "weblayer/browser/profile_impl.h"
#include "weblayer/browser/signin_url_loader_throttle.h"
#include "weblayer/browser/tab_impl.h"
#include "weblayer/public/google_accounts_delegate.h"
#include "weblayer/public/navigation_controller.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 {
constexpr char kGaiaDomain[] = "fakegaia.com";
constexpr char kGoogleAccountsPath[] = "/manageaccounts";
constexpr char kGoogleAccountsRedirectPath[] = "/manageaccounts-redirect";
} // namespace
class GoogleAccountsBrowserTest : public WebLayerBrowserTest,
public GoogleAccountsDelegate {
public:
// WebLayerBrowserTest:
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
shell()->tab()->SetGoogleAccountsDelegate(this);
}
void SetUpCommandLine(base::CommandLine* command_line) override {
https_server_.RegisterRequestHandler(base::BindRepeating(
&GoogleAccountsBrowserTest::HandleGoogleAccountsRequest,
base::Unretained(this)));
net::test_server::RegisterDefaultHandlers(&https_server_);
ASSERT_TRUE(https_server_.Start());
command_line->AppendSwitchASCII(switches::kGaiaUrl, GetGaiaURL("/").spec());
command_line->AppendSwitch("ignore-certificate-errors");
}
// GoogleAccountsDelegate:
void OnGoogleAccountsRequest(
const signin::ManageAccountsParams& params) override {
params_ = params;
if (run_loop_)
run_loop_->Quit();
}
std::string GetGaiaId() override { return ""; }
const signin::ManageAccountsParams& WaitForGoogleAccounts() {
if (!params_) {
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
}
EXPECT_TRUE(params_.has_value());
return params_.value();
}
GURL GetGaiaURL(const std::string& path) {
return https_server_.GetURL(kGaiaDomain, path);
}
GURL GetNonGaiaURL(const std::string& path) {
return https_server_.GetURL(path);
}
bool HasReceivedGoogleAccountsResponse() { return params_.has_value(); }
std::string GetBody() {
return ExecuteScript(shell(), "document.body.innerText", true).GetString();
}
protected:
std::string response_header_;
private:
std::unique_ptr<net::test_server::HttpResponse> HandleGoogleAccountsRequest(
const net::test_server::HttpRequest& request) {
std::string path = request.GetURL().path();
if (path != kSignOutPath && path != kGoogleAccountsPath &&
path != kGoogleAccountsRedirectPath) {
return nullptr;
}
auto http_response =
std::make_unique<net::test_server::BasicHttpResponse>();
if (path == kGoogleAccountsRedirectPath) {
http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
http_response->AddCustomHeader(
"Location",
base::UnescapeBinaryURLComponent(request.GetURL().query_piece()));
} else {
http_response->set_code(net::HTTP_OK);
}
if (base::Contains(request.headers, signin::kChromeConnectedHeader)) {
http_response->AddCustomHeader(signin::kChromeManageAccountsHeader,
response_header_);
}
http_response->set_content("");
return http_response;
}
net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
absl::optional<signin::ManageAccountsParams> params_;
std::unique_ptr<base::RunLoop> run_loop_;
};
IN_PROC_BROWSER_TEST_F(GoogleAccountsBrowserTest, Basic) {
response_header_ =
"action=ADDSESSION,email=foo@bar.com,"
"continue_url=https://blah.com,is_same_tab=true";
NavigateAndWaitForCompletion(GetGaiaURL(kGoogleAccountsPath), shell());
const signin::ManageAccountsParams& params = WaitForGoogleAccounts();
EXPECT_EQ(params.service_type, signin::GAIA_SERVICE_TYPE_ADDSESSION);
EXPECT_EQ(params.email, "foo@bar.com");
EXPECT_EQ(params.continue_url, "https://blah.com");
EXPECT_TRUE(params.is_same_tab);
}
IN_PROC_BROWSER_TEST_F(GoogleAccountsBrowserTest, NonGaiaUrl) {
response_header_ = "action=ADDSESSION";
NavigateAndWaitForCompletion(GetNonGaiaURL(kGoogleAccountsPath), shell());
// Navigate again to make sure the manage accounts response would have been
// received.
NavigateAndWaitForCompletion(GetNonGaiaURL("/echo"), shell());
EXPECT_FALSE(HasReceivedGoogleAccountsResponse());
}
IN_PROC_BROWSER_TEST_F(GoogleAccountsBrowserTest, RedirectFromGaiaURL) {
response_header_ = "action=SIGNUP";
GURL final_url = GetGaiaURL(kGoogleAccountsPath);
TestNavigationObserver test_observer(
final_url, TestNavigationObserver::NavigationEvent::kCompletion,
shell()->tab());
shell()->tab()->GetNavigationController()->Navigate(GetNonGaiaURL(
base::StrCat({kGoogleAccountsRedirectPath, "?", final_url.spec()})));
test_observer.Wait();
const signin::ManageAccountsParams& params = WaitForGoogleAccounts();
EXPECT_EQ(params.service_type, signin::GAIA_SERVICE_TYPE_SIGNUP);
}
IN_PROC_BROWSER_TEST_F(GoogleAccountsBrowserTest, RedirectToGaiaURL) {
response_header_ = "action=SIGNUP";
GURL final_url = GetNonGaiaURL(kGoogleAccountsPath);
TestNavigationObserver test_observer(
final_url, TestNavigationObserver::NavigationEvent::kCompletion,
shell()->tab());
shell()->tab()->GetNavigationController()->Navigate(GetGaiaURL(
base::StrCat({kGoogleAccountsRedirectPath, "?", final_url.spec()})));
test_observer.Wait();
const signin::ManageAccountsParams& params = WaitForGoogleAccounts();
EXPECT_EQ(params.service_type, signin::GAIA_SERVICE_TYPE_SIGNUP);
}
IN_PROC_BROWSER_TEST_F(GoogleAccountsBrowserTest, AddsQueryParamsToSignoutURL) {
response_header_ = "action=SIGNUP";
// Sign out URL on the GAIA domain will get a query param added to it.
GURL sign_out_url = GetGaiaURL(kSignOutPath);
GURL sign_out_url_with_params =
net::AppendQueryParameter(sign_out_url, "manage", "true");
{
TestNavigationObserver test_observer(
sign_out_url_with_params,
TestNavigationObserver::NavigationEvent::kCompletion, shell()->tab());
shell()->tab()->GetNavigationController()->Navigate(sign_out_url);
test_observer.Wait();
}
// Other URLs will not have query param added.
NavigateAndWaitForCompletion(GetGaiaURL(kGoogleAccountsPath), shell());
NavigateAndWaitForCompletion(GetNonGaiaURL(kSignOutPath), shell());
// Redirecting to sign out URL will also add params.
{
TestNavigationObserver test_observer(
sign_out_url_with_params,
TestNavigationObserver::NavigationEvent::kCompletion, shell()->tab());
shell()->tab()->GetNavigationController()->Navigate(
GetNonGaiaURL("/server-redirect?" + sign_out_url.spec()));
test_observer.Wait();
}
}
IN_PROC_BROWSER_TEST_F(GoogleAccountsBrowserTest, AddsRequestHeaderToGaiaURLs) {
const std::string path =
base::StrCat({"/echoheader?", signin::kChromeConnectedHeader});
NavigateAndWaitForCompletion(GetGaiaURL(path), shell());
EXPECT_EQ(GetBody(),
"source=WebLayer,mode=3,enable_account_consistency=true,"
"consistency_enabled_by_default=false");
// Non GAIA URL should not get the header.
NavigateAndWaitForCompletion(GetNonGaiaURL(path), shell());
EXPECT_EQ(GetBody(), "None");
}
class IncognitoGoogleAccountsBrowserTest : public GoogleAccountsBrowserTest {
public:
IncognitoGoogleAccountsBrowserTest() { SetShellStartsInIncognitoMode(); }
};
IN_PROC_BROWSER_TEST_F(IncognitoGoogleAccountsBrowserTest,
HeaderAddedForIncognitoBrowser) {
const std::string path =
base::StrCat({"/echoheader?", signin::kChromeConnectedHeader});
NavigateAndWaitForCompletion(GetGaiaURL(path), shell());
EXPECT_EQ(GetBody(),
"source=WebLayer,mode=3,enable_account_consistency=true,"
"consistency_enabled_by_default=false");
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/google_accounts_browsertest.cc | C++ | unknown | 8,658 |
// 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/google_accounts_callback_proxy.h"
#include "base/android/jni_string.h"
#include "components/signin/core/browser/signin_header_helper.h"
#include "weblayer/browser/java/jni/GoogleAccountsCallbackProxy_jni.h"
#include "weblayer/public/tab.h"
using base::android::AttachCurrentThread;
using base::android::ConvertUTF8ToJavaString;
namespace weblayer {
GoogleAccountsCallbackProxy::GoogleAccountsCallbackProxy(JNIEnv* env,
jobject obj,
Tab* tab)
: tab_(tab), java_impl_(env, obj) {
tab_->SetGoogleAccountsDelegate(this);
}
GoogleAccountsCallbackProxy::~GoogleAccountsCallbackProxy() {
tab_->SetGoogleAccountsDelegate(nullptr);
}
void GoogleAccountsCallbackProxy::OnGoogleAccountsRequest(
const signin::ManageAccountsParams& params) {
JNIEnv* env = AttachCurrentThread();
Java_GoogleAccountsCallbackProxy_onGoogleAccountsRequest(
env, java_impl_, params.service_type,
ConvertUTF8ToJavaString(env, params.email),
ConvertUTF8ToJavaString(env, params.continue_url), params.is_same_tab);
}
std::string GoogleAccountsCallbackProxy::GetGaiaId() {
return base::android::ConvertJavaStringToUTF8(
Java_GoogleAccountsCallbackProxy_getGaiaId(AttachCurrentThread(),
java_impl_));
}
static jlong JNI_GoogleAccountsCallbackProxy_CreateGoogleAccountsCallbackProxy(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& proxy,
jlong tab) {
return reinterpret_cast<jlong>(
new GoogleAccountsCallbackProxy(env, proxy, reinterpret_cast<Tab*>(tab)));
}
static void JNI_GoogleAccountsCallbackProxy_DeleteGoogleAccountsCallbackProxy(
JNIEnv* env,
jlong proxy) {
delete reinterpret_cast<GoogleAccountsCallbackProxy*>(proxy);
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/google_accounts_callback_proxy.cc | C++ | unknown | 2,043 |
// 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_GOOGLE_ACCOUNTS_CALLBACK_PROXY_H_
#define WEBLAYER_BROWSER_GOOGLE_ACCOUNTS_CALLBACK_PROXY_H_
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "base/memory/raw_ptr.h"
#include "weblayer/public/google_accounts_delegate.h"
namespace weblayer {
class Tab;
class GoogleAccountsCallbackProxy : public GoogleAccountsDelegate {
public:
GoogleAccountsCallbackProxy(JNIEnv* env, jobject obj, Tab* tab);
~GoogleAccountsCallbackProxy() override;
// GoogleAccountsDelegate:
void OnGoogleAccountsRequest(
const signin::ManageAccountsParams& params) override;
std::string GetGaiaId() override;
private:
raw_ptr<Tab> tab_;
base::android::ScopedJavaGlobalRef<jobject> java_impl_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_GOOGLE_ACCOUNTS_CALLBACK_PROXY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/google_accounts_callback_proxy.h | C++ | unknown | 972 |
// 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/heavy_ad_service_factory.h"
#include "base/no_destructor.h"
#include "components/heavy_ad_intervention/heavy_ad_service.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "content/public/browser/browser_context.h"
namespace weblayer {
// static
heavy_ad_intervention::HeavyAdService*
HeavyAdServiceFactory::GetForBrowserContext(content::BrowserContext* context) {
return static_cast<heavy_ad_intervention::HeavyAdService*>(
GetInstance()->GetServiceForBrowserContext(context, true));
}
// static
HeavyAdServiceFactory* HeavyAdServiceFactory::GetInstance() {
static base::NoDestructor<HeavyAdServiceFactory> factory;
return factory.get();
}
HeavyAdServiceFactory::HeavyAdServiceFactory()
: BrowserContextKeyedServiceFactory(
"HeavyAdService",
BrowserContextDependencyManager::GetInstance()) {}
HeavyAdServiceFactory::~HeavyAdServiceFactory() = default;
KeyedService* HeavyAdServiceFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new heavy_ad_intervention::HeavyAdService();
}
content::BrowserContext* HeavyAdServiceFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/heavy_ad_service_factory.cc | C++ | unknown | 1,437 |
// 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_HEAVY_AD_SERVICE_FACTORY_H_
#define WEBLAYER_BROWSER_HEAVY_AD_SERVICE_FACTORY_H_
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
namespace content {
class BrowserContext;
}
namespace heavy_ad_intervention {
class HeavyAdService;
}
namespace weblayer {
class HeavyAdServiceFactory : public BrowserContextKeyedServiceFactory {
public:
HeavyAdServiceFactory(const HeavyAdServiceFactory&) = delete;
HeavyAdServiceFactory& operator=(const HeavyAdServiceFactory&) = delete;
// Gets the HeavyAdService instance for |context|.
static heavy_ad_intervention::HeavyAdService* GetForBrowserContext(
content::BrowserContext* context);
static HeavyAdServiceFactory* GetInstance();
private:
friend class base::NoDestructor<HeavyAdServiceFactory>;
HeavyAdServiceFactory();
~HeavyAdServiceFactory() override;
// BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
content::BrowserContext* GetBrowserContextToUse(
content::BrowserContext* context) const override;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_HEAVY_AD_SERVICE_FACTORY_H_
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/heavy_ad_service_factory.h | C++ | unknown | 1,393 |
// 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/host_content_settings_map_factory.h"
#include <utility>
#include "base/feature_list.h"
#include "components/content_settings/core/browser/content_settings_pref_provider.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
namespace weblayer {
HostContentSettingsMapFactory::HostContentSettingsMapFactory()
: RefcountedBrowserContextKeyedServiceFactory(
"HostContentSettingsMap",
BrowserContextDependencyManager::GetInstance()) {}
HostContentSettingsMapFactory::~HostContentSettingsMapFactory() = default;
// static
HostContentSettingsMap* HostContentSettingsMapFactory::GetForBrowserContext(
content::BrowserContext* browser_context) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
return static_cast<HostContentSettingsMap*>(
GetInstance()->GetServiceForBrowserContext(browser_context, true).get());
}
// static
HostContentSettingsMapFactory* HostContentSettingsMapFactory::GetInstance() {
return base::Singleton<HostContentSettingsMapFactory>::get();
}
scoped_refptr<RefcountedKeyedService>
HostContentSettingsMapFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
scoped_refptr<HostContentSettingsMap> settings_map =
base::MakeRefCounted<HostContentSettingsMap>(
user_prefs::UserPrefs::Get(context), context->IsOffTheRecord(),
/*store_last_modified=*/true,
/*restore_session=*/false,
/*should_record_metrics=*/!context->IsOffTheRecord());
return settings_map;
}
content::BrowserContext* HostContentSettingsMapFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return context;
}
} // namespace weblayer
| Zhao-PengFei35/chromium_src_4 | weblayer/browser/host_content_settings_map_factory.cc | C++ | unknown | 2,176 |