0

Convert Callback to {Once,Repeating}Callback in //content/browser.

Use OnceCallback where possible, and use BindRepeating() where it is
meant to be a RepeatingCallback.

Majority of this change is a few typedefs that are very widely used:
- LoadedCallback
- ValidateTokenCallback
- ValidateRegistrationCallback
- GotDataCallback**

** Especially this one.

R=blundell@chromium.org, clamy@chromium.org, marq@chromium.org
TBR=clamy

Bug: 1007760
Change-Id: I3e6b2bfbc1ff5d36a96628da1163f6a37fb2b204
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1943327
Commit-Queue: danakj <danakj@chromium.org>
Reviewed-by: Mark Cogan <marq@chromium.org>
Reviewed-by: Colin Blundell <blundell@chromium.org>
Cr-Commit-Position: refs/heads/master@{#720205}
This commit is contained in:
danakj
2019-11-29 15:43:04 +00:00
committed by Commit Bot
parent 27a2802e5e
commit f4b9e94bcc
145 changed files with 945 additions and 920 deletions
android_webview/browser
chrome
browser
accessibility
apps
chrome_content_browser_client.ccchrome_content_browser_client.hchrome_service_worker_browsertest.cc
chromeos
devtools
push_messaging
search
sharing
sync
test
integration
ui
web_applications
test
components
content
extensions/shell/browser
ios

@@ -887,7 +887,7 @@ AwContentBrowserClient::CreateLoginDelegate(
bool AwContentBrowserClient::HandleExternalProtocol( bool AwContentBrowserClient::HandleExternalProtocol(
const GURL& url, const GURL& url,
content::WebContents::Getter web_contents_getter, content::WebContents::OnceGetter web_contents_getter,
int child_id, int child_id,
content::NavigationUIData* navigation_data, content::NavigationUIData* navigation_data,
bool is_main_frame, bool is_main_frame,

@@ -183,7 +183,7 @@ class AwContentBrowserClient : public content::ContentBrowserClient {
LoginAuthRequiredCallback auth_required_callback) override; LoginAuthRequiredCallback auth_required_callback) override;
bool HandleExternalProtocol( bool HandleExternalProtocol(
const GURL& url, const GURL& url,
content::WebContents::Getter web_contents_getter, content::WebContents::OnceGetter web_contents_getter,
int child_id, int child_id,
content::NavigationUIData* navigation_data, content::NavigationUIData* navigation_data,
bool is_main_frame, bool is_main_frame,

@@ -163,7 +163,7 @@ bool ShouldHandleAccessibilityRequestCallback(const std::string& path) {
void HandleAccessibilityRequestCallback( void HandleAccessibilityRequestCallback(
content::BrowserContext* current_context, content::BrowserContext* current_context,
const std::string& path, const std::string& path,
const content::WebUIDataSource::GotDataCallback& callback) { content::WebUIDataSource::GotDataCallback callback) {
DCHECK(ShouldHandleAccessibilityRequestCallback(path)); DCHECK(ShouldHandleAccessibilityRequestCallback(path));
base::DictionaryValue data; base::DictionaryValue data;
@@ -250,7 +250,7 @@ void HandleAccessibilityRequestCallback(
std::string json_string; std::string json_string;
base::JSONWriter::Write(data, &json_string); base::JSONWriter::Write(data, &json_string);
callback.Run(base::RefCountedString::TakeString(&json_string)); std::move(callback).Run(base::RefCountedString::TakeString(&json_string));
} }
bool MatchesPropertyFilters( bool MatchesPropertyFilters(

@@ -24,7 +24,7 @@ namespace apps {
namespace { namespace {
void LoadDefaultImage(const content::URLDataSource::GotDataCallback& callback) { void LoadDefaultImage(content::URLDataSource::GotDataCallback callback) {
base::StringPiece contents = base::StringPiece contents =
ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale( ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(
IDR_APP_DEFAULT_ICON, apps_util::GetPrimaryDisplayUIScaleFactor()); IDR_APP_DEFAULT_ICON, apps_util::GetPrimaryDisplayUIScaleFactor());
@@ -32,18 +32,18 @@ void LoadDefaultImage(const content::URLDataSource::GotDataCallback& callback) {
base::RefCountedBytes* image_bytes = new base::RefCountedBytes(); base::RefCountedBytes* image_bytes = new base::RefCountedBytes();
image_bytes->data().assign(contents.data(), image_bytes->data().assign(contents.data(),
contents.data() + contents.size()); contents.data() + contents.size());
callback.Run(image_bytes); std::move(callback).Run(image_bytes);
} }
void RunCallback(const content::URLDataSource::GotDataCallback& callback, void RunCallback(content::URLDataSource::GotDataCallback callback,
apps::mojom::IconValuePtr iv) { apps::mojom::IconValuePtr iv) {
if (!iv->compressed.has_value() || iv->compressed.value().empty()) { if (!iv->compressed.has_value() || iv->compressed.value().empty()) {
LoadDefaultImage(callback); LoadDefaultImage(std::move(callback));
return; return;
} }
base::RefCountedBytes* image_bytes = base::RefCountedBytes* image_bytes =
new base::RefCountedBytes(iv->compressed.value()); new base::RefCountedBytes(iv->compressed.value());
callback.Run(image_bytes); std::move(callback).Run(image_bytes);
} }
} // namespace } // namespace
@@ -59,7 +59,7 @@ std::string AppIconSource::GetSource() {
void AppIconSource::StartDataRequest( void AppIconSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
const std::string path_lower = const std::string path_lower =
base::ToLowerASCII(content::URLDataSource::URLToRequestPath(url)); base::ToLowerASCII(content::URLDataSource::URLToRequestPath(url));
std::vector<std::string> path_parts = base::SplitString( std::vector<std::string> path_parts = base::SplitString(
@@ -67,7 +67,7 @@ void AppIconSource::StartDataRequest(
// Check data exists, load default image if it doesn't. // Check data exists, load default image if it doesn't.
if (path_lower.empty() || path_parts.size() < 2) { if (path_lower.empty() || path_parts.size() < 2) {
LoadDefaultImage(callback); LoadDefaultImage(std::move(callback));
return; return;
} }
@@ -76,7 +76,7 @@ void AppIconSource::StartDataRequest(
std::string size_param = path_parts[1]; std::string size_param = path_parts[1];
int size = 0; int size = 0;
if (!base::StringToInt(size_param, &size)) { if (!base::StringToInt(size_param, &size)) {
LoadDefaultImage(callback); LoadDefaultImage(std::move(callback));
return; return;
} }
constexpr bool quantize_to_supported_scale_factor = true; constexpr bool quantize_to_supported_scale_factor = true;
@@ -86,7 +86,7 @@ void AppIconSource::StartDataRequest(
apps::AppServiceProxy* app_service_proxy = apps::AppServiceProxy* app_service_proxy =
apps::AppServiceProxyFactory::GetForProfile(profile_); apps::AppServiceProxyFactory::GetForProfile(profile_);
if (!app_service_proxy) { if (!app_service_proxy) {
LoadDefaultImage(callback); LoadDefaultImage(std::move(callback));
return; return;
} }
@@ -95,7 +95,8 @@ void AppIconSource::StartDataRequest(
constexpr bool allow_placeholder_icon = false; constexpr bool allow_placeholder_icon = false;
app_service_proxy->LoadIcon( app_service_proxy->LoadIcon(
app_type, app_id, apps::mojom::IconCompression::kCompressed, size_in_dip, app_type, app_id, apps::mojom::IconCompression::kCompressed, size_in_dip,
allow_placeholder_icon, base::BindOnce(&RunCallback, callback)); allow_placeholder_icon,
base::BindOnce(&RunCallback, std::move(callback)));
} }
std::string AppIconSource::GetMimeType(const std::string&) { std::string AppIconSource::GetMimeType(const std::string&) {

@@ -39,7 +39,7 @@ class AppIconSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string&) override; std::string GetMimeType(const std::string&) override;
bool AllowCaching() override; bool AllowCaching() override;
bool ShouldReplaceExistingSource() override; bool ShouldReplaceExistingSource() override;

@@ -940,13 +940,13 @@ chrome::mojom::PrerenderCanceler* GetPrerenderCanceller(
} }
void LaunchURL(const GURL& url, void LaunchURL(const GURL& url,
const content::WebContents::Getter& web_contents_getter, content::WebContents::OnceGetter web_contents_getter,
ui::PageTransition page_transition, ui::PageTransition page_transition,
bool has_user_gesture, bool has_user_gesture,
const base::Optional<url::Origin>& initiating_origin) { const base::Optional<url::Origin>& initiating_origin) {
// If there is no longer a WebContents, the request may have raced with tab // If there is no longer a WebContents, the request may have raced with tab
// closing. Don't fire the external request. (It may have been a prerender.) // closing. Don't fire the external request. (It may have been a prerender.)
content::WebContents* web_contents = web_contents_getter.Run(); content::WebContents* web_contents = std::move(web_contents_getter).Run();
if (!web_contents) if (!web_contents)
return; return;
@@ -4768,7 +4768,7 @@ ChromeContentBrowserClient::CreateLoginDelegate(
bool ChromeContentBrowserClient::HandleExternalProtocol( bool ChromeContentBrowserClient::HandleExternalProtocol(
const GURL& url, const GURL& url,
content::WebContents::Getter web_contents_getter, content::WebContents::OnceGetter web_contents_getter,
int child_id, int child_id,
content::NavigationUIData* navigation_data, content::NavigationUIData* navigation_data,
bool is_main_frame, bool is_main_frame,
@@ -4799,8 +4799,8 @@ bool ChromeContentBrowserClient::HandleExternalProtocol(
base::PostTask( base::PostTask(
FROM_HERE, {BrowserThread::UI}, FROM_HERE, {BrowserThread::UI},
base::BindOnce(&LaunchURL, url, web_contents_getter, page_transition, base::BindOnce(&LaunchURL, url, std::move(web_contents_getter),
has_user_gesture, initiating_origin)); page_transition, has_user_gesture, initiating_origin));
return true; return true;
} }

@@ -549,7 +549,7 @@ class ChromeContentBrowserClient : public content::ContentBrowserClient {
LoginAuthRequiredCallback auth_required_callback) override; LoginAuthRequiredCallback auth_required_callback) override;
bool HandleExternalProtocol( bool HandleExternalProtocol(
const GURL& url, const GURL& url,
content::WebContents::Getter web_contents_getter, content::WebContents::OnceGetter web_contents_getter,
int child_id, int child_id,
content::NavigationUIData* navigation_data, content::NavigationUIData* navigation_data,
bool is_main_frame, bool is_main_frame,

@@ -699,9 +699,9 @@ class StaticURLDataSource : public content::URLDataSource {
std::string GetSource() override { return source_; } std::string GetSource() override { return source_; }
void StartDataRequest(const GURL& url, void StartDataRequest(const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const GotDataCallback& callback) override { GotDataCallback callback) override {
std::string data(content_); std::string data(content_);
callback.Run(base::RefCountedString::TakeString(&data)); std::move(callback).Run(base::RefCountedString::TakeString(&data));
} }
std::string GetMimeType(const std::string& path) override { std::string GetMimeType(const std::string& path) override {
return "application/javascript"; return "application/javascript";

@@ -38,23 +38,24 @@ class TestFilesDataSource : public content::URLDataSource {
~TestFilesDataSource() override {} ~TestFilesDataSource() override {}
private: private:
// This has to match kTestResourceURL // This has to match TestResourceUrl()
std::string GetSource() override { return "file_manager_test"; } std::string GetSource() override { return "file_manager_test"; }
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override { content::URLDataSource::GotDataCallback callback) override {
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
base::PostTask(FROM_HERE, base::PostTask(
{base::ThreadPool(), base::MayBlock(), FROM_HERE,
base::TaskPriority::USER_BLOCKING}, {base::ThreadPool(), base::MayBlock(),
base::BindOnce(&TestFilesDataSource::ReadFile, base::TaskPriority::USER_BLOCKING},
base::Unretained(this), path, callback)); base::BindOnce(&TestFilesDataSource::ReadFile, base::Unretained(this),
path, std::move(callback)));
} }
void ReadFile(const std::string& path, void ReadFile(const std::string& path,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
if (source_root_.empty()) { if (source_root_.empty()) {
CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_)); CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_));
} }
@@ -85,7 +86,7 @@ class TestFilesDataSource : public content::URLDataSource {
scoped_refptr<base::RefCountedString> response = scoped_refptr<base::RefCountedString> response =
base::RefCountedString::TakeString(&content); base::RefCountedString::TakeString(&content);
callback.Run(response.get()); std::move(callback).Run(response.get());
} }
// It currently only serves HTML/JS/CSS. // It currently only serves HTML/JS/CSS.
@@ -138,6 +139,11 @@ class TestWebUIProvider
base::LazyInstance<TestWebUIProvider>::DestructorAtExit test_webui_provider_ = base::LazyInstance<TestWebUIProvider>::DestructorAtExit test_webui_provider_ =
LAZY_INSTANCE_INITIALIZER; LAZY_INSTANCE_INITIALIZER;
static const GURL TestResourceUrl() {
static GURL url(content::GetWebUIURLString("file_manager_test"));
return url;
}
} // namespace } // namespace
FileManagerJsTestBase::FileManagerJsTestBase(const base::FilePath& base_path) FileManagerJsTestBase::FileManagerJsTestBase(const base::FilePath& base_path)
@@ -145,9 +151,6 @@ FileManagerJsTestBase::FileManagerJsTestBase(const base::FilePath& base_path)
FileManagerJsTestBase::~FileManagerJsTestBase() {} FileManagerJsTestBase::~FileManagerJsTestBase() {}
const std::string FileManagerJsTestBase::kTestResourceURL =
content::GetWebUIURLString("file_manager_test");
void FileManagerJsTestBase::RunTest(const base::FilePath& file) { void FileManagerJsTestBase::RunTest(const base::FilePath& file) {
base::FilePath root_path; base::FilePath root_path;
ASSERT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &root_path)); ASSERT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &root_path));
@@ -196,15 +199,14 @@ void FileManagerJsTestBase::SetUpOnMainThread() {
std::make_unique<TestChromeWebUIControllerFactory>(); std::make_unique<TestChromeWebUIControllerFactory>();
content::WebUIControllerFactory::RegisterFactory( content::WebUIControllerFactory::RegisterFactory(
webui_controller_factory_.get()); webui_controller_factory_.get());
webui_controller_factory_->AddFactoryOverride(GURL(kTestResourceURL).host(), webui_controller_factory_->AddFactoryOverride(TestResourceUrl().host(),
test_webui_provider_.Pointer()); test_webui_provider_.Pointer());
} }
void FileManagerJsTestBase::TearDownOnMainThread() { void FileManagerJsTestBase::TearDownOnMainThread() {
InProcessBrowserTest::TearDownOnMainThread(); InProcessBrowserTest::TearDownOnMainThread();
webui_controller_factory_->RemoveFactoryOverride( webui_controller_factory_->RemoveFactoryOverride(TestResourceUrl().host());
GURL(kTestResourceURL).host());
content::WebUIControllerFactory::UnregisterFactoryForTesting( content::WebUIControllerFactory::UnregisterFactoryForTesting(
webui_controller_factory_.get()); webui_controller_factory_.get());

@@ -32,17 +32,21 @@ struct ImageInfo {
ImageInfo(const base::FilePath& file_path, ImageInfo(const base::FilePath& file_path,
int pixels_per_side, int pixels_per_side,
ImageDecoder::ImageCodec image_codec, ImageDecoder::ImageCodec image_codec,
const LoadedCallback& loaded_cb) LoadedCallback loaded_cb)
: file_path(file_path), : file_path(file_path),
pixels_per_side(pixels_per_side), pixels_per_side(pixels_per_side),
image_codec(image_codec), image_codec(image_codec),
loaded_cb(loaded_cb) {} loaded_cb(std::move(loaded_cb)) {}
ImageInfo(ImageInfo&&) = default;
ImageInfo& operator=(ImageInfo&&) = default;
~ImageInfo() {} ~ImageInfo() {}
const base::FilePath file_path; base::FilePath file_path;
const int pixels_per_side; int pixels_per_side;
const ImageDecoder::ImageCodec image_codec; ImageDecoder::ImageCodec image_codec;
const LoadedCallback loaded_cb; LoadedCallback loaded_cb;
}; };
// Crops |image| to the square format and downsizes the image to // Crops |image| to the square format and downsizes the image to
@@ -106,10 +110,10 @@ user_manager::UserImage::ImageFormat ChooseImageFormatFromCodec(
class UserImageRequest : public ImageDecoder::ImageRequest { class UserImageRequest : public ImageDecoder::ImageRequest {
public: public:
UserImageRequest( UserImageRequest(
const ImageInfo& image_info, ImageInfo image_info,
const std::string& image_data, const std::string& image_data,
scoped_refptr<base::SequencedTaskRunner> background_task_runner) scoped_refptr<base::SequencedTaskRunner> background_task_runner)
: image_info_(image_info), : image_info_(std::move(image_info)),
// TODO(crbug.com/593251): Remove the data copy here. // TODO(crbug.com/593251): Remove the data copy here.
image_data_(new base::RefCountedBytes( image_data_(new base::RefCountedBytes(
reinterpret_cast<const unsigned char*>(image_data.data()), reinterpret_cast<const unsigned char*>(image_data.data()),
@@ -134,7 +138,7 @@ class UserImageRequest : public ImageDecoder::ImageRequest {
bool image_bytes_regenerated); bool image_bytes_regenerated);
private: private:
const ImageInfo image_info_; ImageInfo image_info_;
scoped_refptr<base::RefCountedBytes> image_data_; scoped_refptr<base::RefCountedBytes> image_data_;
scoped_refptr<base::SequencedTaskRunner> background_task_runner_; scoped_refptr<base::SequencedTaskRunner> background_task_runner_;
@@ -200,19 +204,20 @@ void UserImageRequest::OnImageFinalized(
image_info_.image_codec == ImageDecoder::ROBUST_PNG_CODEC || image_info_.image_codec == ImageDecoder::ROBUST_PNG_CODEC ||
image_bytes_regenerated) image_bytes_regenerated)
user_image->MarkAsSafe(); user_image->MarkAsSafe();
image_info_.loaded_cb.Run(std::move(user_image)); std::move(image_info_.loaded_cb).Run(std::move(user_image));
delete this; delete this;
} }
void UserImageRequest::OnDecodeImageFailed() { void UserImageRequest::OnDecodeImageFailed() {
image_info_.loaded_cb.Run(base::WrapUnique(new user_manager::UserImage)); std::move(image_info_.loaded_cb)
.Run(base::WrapUnique(new user_manager::UserImage));
delete this; delete this;
} }
// Starts decoding the image with ImageDecoder for the image |data| if // Starts decoding the image with ImageDecoder for the image |data| if
// |data_is_ready| is true. // |data_is_ready| is true.
void DecodeImage( void DecodeImage(
const ImageInfo& image_info, ImageInfo image_info,
scoped_refptr<base::SequencedTaskRunner> background_task_runner, scoped_refptr<base::SequencedTaskRunner> background_task_runner,
const std::string* data, const std::string* data,
bool data_is_ready) { bool data_is_ready) {
@@ -220,15 +225,15 @@ void DecodeImage(
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, FROM_HERE,
base::BindOnce( base::BindOnce(
image_info.loaded_cb, std::move(image_info.loaded_cb),
base::Passed(base::WrapUnique(new user_manager::UserImage)))); base::Passed(base::WrapUnique(new user_manager::UserImage))));
return; return;
} }
UserImageRequest* image_request = ImageDecoder::ImageCodec codec = image_info.image_codec;
new UserImageRequest(image_info, *data, background_task_runner); UserImageRequest* image_request = new UserImageRequest(
ImageDecoder::StartWithOptions(image_request, *data, image_info.image_codec, std::move(image_info), *data, background_task_runner);
false); ImageDecoder::StartWithOptions(image_request, *data, codec, false);
} }
} // namespace } // namespace
@@ -238,14 +243,15 @@ void StartWithFilePath(
const base::FilePath& file_path, const base::FilePath& file_path,
ImageDecoder::ImageCodec image_codec, ImageDecoder::ImageCodec image_codec,
int pixels_per_side, int pixels_per_side,
const LoadedCallback& loaded_cb) { LoadedCallback loaded_cb) {
std::string* data = new std::string; std::string* data = new std::string;
base::PostTaskAndReplyWithResult( base::PostTaskAndReplyWithResult(
background_task_runner.get(), FROM_HERE, background_task_runner.get(), FROM_HERE,
base::Bind(&base::ReadFileToString, file_path, data), base::BindOnce(&base::ReadFileToString, file_path, data),
base::Bind(&DecodeImage, base::BindOnce(&DecodeImage,
ImageInfo(file_path, pixels_per_side, image_codec, loaded_cb), ImageInfo(file_path, pixels_per_side, image_codec,
background_task_runner, base::Owned(data))); std::move(loaded_cb)),
background_task_runner, base::Owned(data)));
} }
void StartWithData( void StartWithData(
@@ -253,10 +259,10 @@ void StartWithData(
std::unique_ptr<std::string> data, std::unique_ptr<std::string> data,
ImageDecoder::ImageCodec image_codec, ImageDecoder::ImageCodec image_codec,
int pixels_per_side, int pixels_per_side,
const LoadedCallback& loaded_cb) { LoadedCallback loaded_cb) {
DecodeImage( DecodeImage(ImageInfo(base::FilePath(), pixels_per_side, image_codec,
ImageInfo(base::FilePath(), pixels_per_side, image_codec, loaded_cb), std::move(loaded_cb)),
background_task_runner, data.get(), true /* data_is_ready */); background_task_runner, data.get(), true /* data_is_ready */);
} }
} // namespace user_image_loader } // namespace user_image_loader

@@ -25,8 +25,8 @@ class UserImage;
namespace chromeos { namespace chromeos {
namespace user_image_loader { namespace user_image_loader {
typedef base::Callback<void(std::unique_ptr<user_manager::UserImage>)> using LoadedCallback =
LoadedCallback; base::OnceCallback<void(std::unique_ptr<user_manager::UserImage>)>;
// Loads an image with |image_codec| in the background and calls |loaded_cb| // Loads an image with |image_codec| in the background and calls |loaded_cb|
// with the resulting UserImage (which may be empty in case of error). If // with the resulting UserImage (which may be empty in case of error). If
@@ -41,13 +41,13 @@ void StartWithFilePath(
const base::FilePath& file_path, const base::FilePath& file_path,
ImageDecoder::ImageCodec image_codec, ImageDecoder::ImageCodec image_codec,
int pixels_per_side, int pixels_per_side,
const LoadedCallback& loaded_cb); LoadedCallback loaded_cb);
void StartWithData( void StartWithData(
scoped_refptr<base::SequencedTaskRunner> background_task_runner, scoped_refptr<base::SequencedTaskRunner> background_task_runner,
std::unique_ptr<std::string> data, std::unique_ptr<std::string> data,
ImageDecoder::ImageCodec image_codec, ImageDecoder::ImageCodec image_codec,
int pixels_per_side, int pixels_per_side,
const LoadedCallback& loaded_cb); LoadedCallback loaded_cb);
} // namespace user_image_loader } // namespace user_image_loader
} // namespace chromeos } // namespace chromeos

@@ -2154,9 +2154,9 @@ class StaticURLDataSource : public content::URLDataSource {
std::string GetSource() override { return source_; } std::string GetSource() override { return source_; }
void StartDataRequest(const GURL& url, void StartDataRequest(const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const GotDataCallback& callback) override { GotDataCallback callback) override {
std::string data(content_); std::string data(content_);
callback.Run(base::RefCountedString::TakeString(&data)); std::move(callback).Run(base::RefCountedString::TakeString(&data));
} }
std::string GetMimeType(const std::string& path) override { std::string GetMimeType(const std::string& path) override {
return "text/html"; return "text/html";

@@ -726,31 +726,33 @@ void PushMessagingServiceImpl::GetSubscriptionInfo(
int64_t service_worker_registration_id, int64_t service_worker_registration_id,
const std::string& sender_id, const std::string& sender_id,
const std::string& subscription_id, const std::string& subscription_id,
const SubscriptionInfoCallback& callback) { SubscriptionInfoCallback callback) {
PushMessagingAppIdentifier app_identifier = PushMessagingAppIdentifier app_identifier =
PushMessagingAppIdentifier::FindByServiceWorker( PushMessagingAppIdentifier::FindByServiceWorker(
profile_, origin, service_worker_registration_id); profile_, origin, service_worker_registration_id);
if (app_identifier.is_null()) { if (app_identifier.is_null()) {
callback.Run(false /* is_valid */, GURL::EmptyGURL() /*endpoint*/, std::move(callback).Run(
std::vector<uint8_t>() /* p256dh */, false /* is_valid */, GURL::EmptyGURL() /*endpoint*/,
std::vector<uint8_t>() /* auth */); std::vector<uint8_t>() /* p256dh */, std::vector<uint8_t>() /* auth */);
return; return;
} }
const GURL endpoint = CreateEndpoint(subscription_id); const GURL endpoint = CreateEndpoint(subscription_id);
const std::string& app_id = app_identifier.app_id(); const std::string& app_id = app_identifier.app_id();
base::Callback<void(bool)> validate_cb = base::Bind( base::OnceCallback<void(bool)> validate_cb =
&PushMessagingServiceImpl::DidValidateSubscription, base::BindOnce(&PushMessagingServiceImpl::DidValidateSubscription,
weak_factory_.GetWeakPtr(), app_id, sender_id, endpoint, callback); weak_factory_.GetWeakPtr(), app_id, sender_id, endpoint,
std::move(callback));
if (PushMessagingAppIdentifier::UseInstanceID(app_id)) { if (PushMessagingAppIdentifier::UseInstanceID(app_id)) {
GetInstanceIDDriver()->GetInstanceID(app_id)->ValidateToken( GetInstanceIDDriver()->GetInstanceID(app_id)->ValidateToken(
NormalizeSenderInfo(sender_id), kGCMScope, subscription_id, NormalizeSenderInfo(sender_id), kGCMScope, subscription_id,
validate_cb); std::move(validate_cb));
} else { } else {
GetGCMDriver()->ValidateRegistration( GetGCMDriver()->ValidateRegistration(
app_id, {NormalizeSenderInfo(sender_id)}, subscription_id, validate_cb); app_id, {NormalizeSenderInfo(sender_id)}, subscription_id,
std::move(validate_cb));
} }
} }
@@ -758,31 +760,32 @@ void PushMessagingServiceImpl::DidValidateSubscription(
const std::string& app_id, const std::string& app_id,
const std::string& sender_id, const std::string& sender_id,
const GURL& endpoint, const GURL& endpoint,
const SubscriptionInfoCallback& callback, SubscriptionInfoCallback callback,
bool is_valid) { bool is_valid) {
if (!is_valid) { if (!is_valid) {
callback.Run(false /* is_valid */, GURL::EmptyGURL() /* endpoint */, std::move(callback).Run(
std::vector<uint8_t>() /* p256dh */, false /* is_valid */, GURL::EmptyGURL() /* endpoint */,
std::vector<uint8_t>() /* auth */); std::vector<uint8_t>() /* p256dh */, std::vector<uint8_t>() /* auth */);
return; return;
} }
GetEncryptionInfoForAppId( GetEncryptionInfoForAppId(
app_id, sender_id, app_id, sender_id,
base::BindOnce(&PushMessagingServiceImpl::DidGetEncryptionInfo, base::BindOnce(&PushMessagingServiceImpl::DidGetEncryptionInfo,
weak_factory_.GetWeakPtr(), endpoint, callback)); weak_factory_.GetWeakPtr(), endpoint,
std::move(callback)));
} }
void PushMessagingServiceImpl::DidGetEncryptionInfo( void PushMessagingServiceImpl::DidGetEncryptionInfo(
const GURL& endpoint, const GURL& endpoint,
const SubscriptionInfoCallback& callback, SubscriptionInfoCallback callback,
std::string p256dh, std::string p256dh,
std::string auth_secret) const { std::string auth_secret) const {
// I/O errors might prevent the GCM Driver from retrieving a key-pair. // I/O errors might prevent the GCM Driver from retrieving a key-pair.
bool is_valid = !p256dh.empty(); bool is_valid = !p256dh.empty();
callback.Run(is_valid, endpoint, std::move(callback).Run(
std::vector<uint8_t>(p256dh.begin(), p256dh.end()), is_valid, endpoint, std::vector<uint8_t>(p256dh.begin(), p256dh.end()),
std::vector<uint8_t>(auth_secret.begin(), auth_secret.end())); std::vector<uint8_t>(auth_secret.begin(), auth_secret.end()));
} }
// Unsubscribe methods --------------------------------------------------------- // Unsubscribe methods ---------------------------------------------------------

@@ -105,7 +105,7 @@ class PushMessagingServiceImpl : public content::PushMessagingService,
int64_t service_worker_registration_id, int64_t service_worker_registration_id,
const std::string& sender_id, const std::string& sender_id,
const std::string& subscription_id, const std::string& subscription_id,
const SubscriptionInfoCallback& callback) override; SubscriptionInfoCallback callback) override;
void Unsubscribe(blink::mojom::PushUnregistrationReason reason, void Unsubscribe(blink::mojom::PushUnregistrationReason reason,
const GURL& requesting_origin, const GURL& requesting_origin,
int64_t service_worker_registration_id, int64_t service_worker_registration_id,
@@ -199,11 +199,11 @@ class PushMessagingServiceImpl : public content::PushMessagingService,
void DidValidateSubscription(const std::string& app_id, void DidValidateSubscription(const std::string& app_id,
const std::string& sender_id, const std::string& sender_id,
const GURL& endpoint, const GURL& endpoint,
const SubscriptionInfoCallback& callback, SubscriptionInfoCallback callback,
bool is_valid); bool is_valid);
void DidGetEncryptionInfo(const GURL& endpoint, void DidGetEncryptionInfo(const GURL& endpoint,
const SubscriptionInfoCallback& callback, SubscriptionInfoCallback callback,
std::string p256dh, std::string p256dh,
std::string auth_secret) const; std::string auth_secret) const;

@@ -329,10 +329,9 @@ std::string ReadBackgroundImageData(const base::FilePath& profile_path) {
return data_string; return data_string;
} }
void ServeBackgroundImageData( void ServeBackgroundImageData(content::URLDataSource::GotDataCallback callback,
const content::URLDataSource::GotDataCallback& callback, std::string data_string) {
std::string data_string) { std::move(callback).Run(base::RefCountedString::TakeString(&data_string));
callback.Run(base::RefCountedString::TakeString(&data_string));
} }
std::string GetLocalNtpPath() { std::string GetLocalNtpPath() {
@@ -665,8 +664,8 @@ class LocalNtpSource::DesktopLogoObserver {
// Get the cached logo. // Get the cached logo.
void GetCachedLogo(LogoService* service, void GetCachedLogo(LogoService* service,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
StartGetLogo(service, callback, /*from_cache=*/true); StartGetLogo(service, std::move(callback), /*from_cache=*/true);
} }
// Get the fresh logo corresponding to a previous request for a cached logo. // Get the fresh logo corresponding to a previous request for a cached logo.
@@ -679,13 +678,13 @@ class LocalNtpSource::DesktopLogoObserver {
// request, or perhaps one newer. // request, or perhaps one newer.
void GetFreshLogo(LogoService* service, void GetFreshLogo(LogoService* service,
int requested_version, int requested_version,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
bool from_cache = (requested_version <= version_finished_); bool from_cache = (requested_version <= version_finished_);
StartGetLogo(service, callback, from_cache); StartGetLogo(service, std::move(callback), from_cache);
} }
private: private:
void OnLogoAvailable(const content::URLDataSource::GotDataCallback& callback, void OnLogoAvailable(content::URLDataSource::GotDataCallback callback,
LogoCallbackReason type, LogoCallbackReason type,
const base::Optional<EncodedLogo>& logo) { const base::Optional<EncodedLogo>& logo) {
scoped_refptr<base::RefCountedString> response; scoped_refptr<base::RefCountedString> response;
@@ -714,21 +713,19 @@ class LocalNtpSource::DesktopLogoObserver {
base::JSONWriter::Write(*ddl, &js); base::JSONWriter::Write(*ddl, &js);
js = "var ddl = " + js + ";"; js = "var ddl = " + js + ";";
response = base::RefCountedString::TakeString(&js); response = base::RefCountedString::TakeString(&js);
callback.Run(response); std::move(callback).Run(response);
} }
void OnCachedLogoAvailable( void OnCachedLogoAvailable(content::URLDataSource::GotDataCallback callback,
const content::URLDataSource::GotDataCallback& callback, LogoCallbackReason type,
LogoCallbackReason type, const base::Optional<EncodedLogo>& logo) {
const base::Optional<EncodedLogo>& logo) { OnLogoAvailable(std::move(callback), type, logo);
OnLogoAvailable(callback, type, logo);
} }
void OnFreshLogoAvailable( void OnFreshLogoAvailable(content::URLDataSource::GotDataCallback callback,
const content::URLDataSource::GotDataCallback& callback, LogoCallbackReason type,
LogoCallbackReason type, const base::Optional<EncodedLogo>& logo) {
const base::Optional<EncodedLogo>& logo) { OnLogoAvailable(std::move(callback), type, logo);
OnLogoAvailable(callback, type, logo);
OnRequestCompleted(type, logo); OnRequestCompleted(type, logo);
} }
@@ -738,21 +735,21 @@ class LocalNtpSource::DesktopLogoObserver {
} }
void StartGetLogo(LogoService* service, void StartGetLogo(LogoService* service,
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
bool from_cache) { bool from_cache) {
EncodedLogoCallback cached, fresh; EncodedLogoCallback cached, fresh;
LogoCallbacks callbacks; LogoCallbacks callbacks;
if (from_cache) { if (from_cache) {
callbacks.on_cached_encoded_logo_available = callbacks.on_cached_encoded_logo_available =
base::BindOnce(&DesktopLogoObserver::OnCachedLogoAvailable, base::BindOnce(&DesktopLogoObserver::OnCachedLogoAvailable,
weak_ptr_factory_.GetWeakPtr(), callback); weak_ptr_factory_.GetWeakPtr(), std::move(callback));
callbacks.on_fresh_encoded_logo_available = callbacks.on_fresh_encoded_logo_available =
base::BindOnce(&DesktopLogoObserver::OnRequestCompleted, base::BindOnce(&DesktopLogoObserver::OnRequestCompleted,
weak_ptr_factory_.GetWeakPtr()); weak_ptr_factory_.GetWeakPtr());
} else { } else {
callbacks.on_fresh_encoded_logo_available = callbacks.on_fresh_encoded_logo_available =
base::BindOnce(&DesktopLogoObserver::OnFreshLogoAvailable, base::BindOnce(&DesktopLogoObserver::OnFreshLogoAvailable,
weak_ptr_factory_.GetWeakPtr(), callback); weak_ptr_factory_.GetWeakPtr(), std::move(callback));
} }
if (!observing()) { if (!observing()) {
++version_started_; ++version_started_;
@@ -826,7 +823,7 @@ std::string LocalNtpSource::GetSource() {
void LocalNtpSource::StartDataRequest( void LocalNtpSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available. // TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
@@ -834,12 +831,13 @@ void LocalNtpSource::StartDataRequest(
std::string stripped_path = StripParameters(path); std::string stripped_path = StripParameters(path);
if (stripped_path == kConfigDataFilename) { if (stripped_path == kConfigDataFilename) {
std::string config_data_js = search_config_provider_->config_data_js(); std::string config_data_js = search_config_provider_->config_data_js();
callback.Run(base::RefCountedString::TakeString(&config_data_js)); std::move(callback).Run(
base::RefCountedString::TakeString(&config_data_js));
return; return;
} }
if (stripped_path == kThemeCSSFilename) { if (stripped_path == kThemeCSSFilename) {
std::string theme_css = GetThemeCSS(profile_); std::string theme_css = GetThemeCSS(profile_);
callback.Run(base::RefCountedString::TakeString(&theme_css)); std::move(callback).Run(base::RefCountedString::TakeString(&theme_css));
return; return;
} }
@@ -849,24 +847,24 @@ void LocalNtpSource::StartDataRequest(
{base::ThreadPool(), base::TaskPriority::USER_VISIBLE, {base::ThreadPool(), base::TaskPriority::USER_VISIBLE,
base::MayBlock()}, base::MayBlock()},
base::BindOnce(&ReadBackgroundImageData, profile_->GetPath()), base::BindOnce(&ReadBackgroundImageData, profile_->GetPath()),
base::BindOnce(&ServeBackgroundImageData, callback)); base::BindOnce(&ServeBackgroundImageData, std::move(callback)));
return; return;
} }
if (stripped_path == kNtpBackgroundCollectionScriptFilename) { if (stripped_path == kNtpBackgroundCollectionScriptFilename) {
if (!ntp_background_service_) { if (!ntp_background_service_) {
callback.Run(nullptr); std::move(callback).Run(nullptr);
return; return;
} }
ntp_background_collections_requests_.emplace_back(base::TimeTicks::Now(), ntp_background_collections_requests_.emplace_back(base::TimeTicks::Now(),
callback); std::move(callback));
ntp_background_service_->FetchCollectionInfo(); ntp_background_service_->FetchCollectionInfo();
return; return;
} }
if (stripped_path == kNtpBackgroundImageScriptFilename) { if (stripped_path == kNtpBackgroundImageScriptFilename) {
if (!ntp_background_service_) { if (!ntp_background_service_) {
callback.Run(nullptr); std::move(callback).Run(nullptr);
return; return;
} }
std::string collection_id_param; std::string collection_id_param;
@@ -874,28 +872,28 @@ void LocalNtpSource::StartDataRequest(
if (net::GetValueForKeyInQuery(path_url, "collection_id", if (net::GetValueForKeyInQuery(path_url, "collection_id",
&collection_id_param)) { &collection_id_param)) {
ntp_background_image_info_requests_.emplace_back(base::TimeTicks::Now(), ntp_background_image_info_requests_.emplace_back(base::TimeTicks::Now(),
callback); std::move(callback));
ntp_background_service_->FetchCollectionImageInfo(collection_id_param); ntp_background_service_->FetchCollectionImageInfo(collection_id_param);
} else { } else {
callback.Run(nullptr); std::move(callback).Run(nullptr);
} }
return; return;
} }
if (stripped_path == kOneGoogleBarScriptFilename) { if (stripped_path == kOneGoogleBarScriptFilename) {
if (!one_google_bar_service_) { if (!one_google_bar_service_) {
callback.Run(nullptr); std::move(callback).Run(nullptr);
} else { } else {
ServeOneGoogleBarWhenAvailable(callback); ServeOneGoogleBarWhenAvailable(std::move(callback));
} }
return; return;
} }
if (stripped_path == kPromoScriptFilename) { if (stripped_path == kPromoScriptFilename) {
if (!promo_service_) { if (!promo_service_) {
callback.Run(nullptr); std::move(callback).Run(nullptr);
} else { } else {
ServePromoWhenAvailable(callback); ServePromoWhenAvailable(std::move(callback));
} }
return; return;
} }
@@ -904,7 +902,7 @@ void LocalNtpSource::StartDataRequest(
// refresh the data until the old data is used. // refresh the data until the old data is used.
if (stripped_path == kSearchSuggestionsScriptFilename) { if (stripped_path == kSearchSuggestionsScriptFilename) {
if (!search_suggest_service_) { if (!search_suggest_service_) {
callback.Run(nullptr); std::move(callback).Run(nullptr);
return; return;
} }
@@ -914,11 +912,12 @@ void LocalNtpSource::StartDataRequest(
if (one_google_bar_service_->language_code() != kEnUSLanguageCode) { if (one_google_bar_service_->language_code() != kEnUSLanguageCode) {
std::string no_suggestions = std::string no_suggestions =
"var searchSuggestions = {suggestionsHtml: ''}"; "var searchSuggestions = {suggestionsHtml: ''}";
callback.Run(base::RefCountedString::TakeString(&no_suggestions)); std::move(callback).Run(
base::RefCountedString::TakeString(&no_suggestions));
return; return;
} }
ServeSearchSuggestionsIfAvailable(callback); ServeSearchSuggestionsIfAvailable(std::move(callback));
pending_search_suggest_request_ = base::TimeTicks::Now(); pending_search_suggest_request_ = base::TimeTicks::Now();
search_suggest_service_->Refresh(); search_suggest_service_->Refresh();
@@ -927,7 +926,7 @@ void LocalNtpSource::StartDataRequest(
if (stripped_path == kDoodleScriptFilename) { if (stripped_path == kDoodleScriptFilename) {
if (!logo_service_) { if (!logo_service_) {
callback.Run(nullptr); std::move(callback).Run(nullptr);
return; return;
} }
@@ -936,9 +935,9 @@ void LocalNtpSource::StartDataRequest(
GURL url = GURL(chrome::kChromeSearchLocalNtpUrl).Resolve(path); GURL url = GURL(chrome::kChromeSearchLocalNtpUrl).Resolve(path);
if (net::GetValueForKeyInQuery(url, "v", &version_string) && if (net::GetValueForKeyInQuery(url, "v", &version_string) &&
base::StringToInt(version_string, &version)) { base::StringToInt(version_string, &version)) {
logo_observer_->GetFreshLogo(logo_service_, version, callback); logo_observer_->GetFreshLogo(logo_service_, version, std::move(callback));
} else { } else {
logo_observer_->GetCachedLogo(logo_service_, callback); logo_observer_->GetCachedLogo(logo_service_, std::move(callback));
} }
return; return;
} }
@@ -1049,7 +1048,7 @@ void LocalNtpSource::StartDataRequest(
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
base::StringPiece html = bundle.GetRawDataResource(IDR_LOCAL_NTP_HTML); base::StringPiece html = bundle.GetRawDataResource(IDR_LOCAL_NTP_HTML);
std::string replaced = ui::ReplaceTemplateExpressions(html, replacements); std::string replaced = ui::ReplaceTemplateExpressions(html, replacements);
callback.Run(base::RefCountedString::TakeString(&replaced)); std::move(callback).Run(base::RefCountedString::TakeString(&replaced));
return; return;
} }
@@ -1064,11 +1063,11 @@ void LocalNtpSource::StartDataRequest(
scoped_refptr<base::RefCountedMemory> response( scoped_refptr<base::RefCountedMemory> response(
ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale( ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytesForScale(
kResources[i].identifier, scale_factor)); kResources[i].identifier, scale_factor));
callback.Run(response.get()); std::move(callback).Run(response.get());
return; return;
} }
} }
callback.Run(nullptr); std::move(callback).Run(nullptr);
} }
std::string LocalNtpSource::GetMimeType(const std::string& path) { std::string LocalNtpSource::GetMimeType(const std::string& path) {
@@ -1149,8 +1148,8 @@ void LocalNtpSource::OnCollectionInfoAvailable() {
result = base::RefCountedString::TakeString(&js); result = base::RefCountedString::TakeString(&js);
base::TimeTicks now = base::TimeTicks::Now(); base::TimeTicks now = base::TimeTicks::Now();
for (const auto& request : ntp_background_collections_requests_) { for (auto& request : ntp_background_collections_requests_) {
request.callback.Run(result); std::move(request.callback).Run(result);
base::TimeDelta delta = now - request.start_time; base::TimeDelta delta = now - request.start_time;
UMA_HISTOGRAM_MEDIUM_TIMES( UMA_HISTOGRAM_MEDIUM_TIMES(
"NewTabPage.BackgroundService.Collections.RequestLatency", delta); "NewTabPage.BackgroundService.Collections.RequestLatency", delta);
@@ -1187,8 +1186,8 @@ void LocalNtpSource::OnCollectionImagesAvailable() {
result = base::RefCountedString::TakeString(&js); result = base::RefCountedString::TakeString(&js);
base::TimeTicks now = base::TimeTicks::Now(); base::TimeTicks now = base::TimeTicks::Now();
for (const auto& request : ntp_background_image_info_requests_) { for (auto& request : ntp_background_image_info_requests_) {
request.callback.Run(result); std::move(request.callback).Run(result);
base::TimeDelta delta = now - request.start_time; base::TimeDelta delta = now - request.start_time;
UMA_HISTOGRAM_MEDIUM_TIMES( UMA_HISTOGRAM_MEDIUM_TIMES(
"NewTabPage.BackgroundService.Images.RequestLatency", delta); "NewTabPage.BackgroundService.Images.RequestLatency", delta);
@@ -1292,7 +1291,7 @@ void LocalNtpSource::OnSearchSuggestServiceShuttingDown() {
} }
void LocalNtpSource::ServeSearchSuggestionsIfAvailable( void LocalNtpSource::ServeSearchSuggestionsIfAvailable(
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
base::Optional<SearchSuggestData> data = base::Optional<SearchSuggestData> data =
search_suggest_service_->search_suggest_data(); search_suggest_service_->search_suggest_data();
@@ -1305,7 +1304,7 @@ void LocalNtpSource::ServeSearchSuggestionsIfAvailable(
base::JSONWriter::Write(*ConvertSearchSuggestDataToDict(data), &js); base::JSONWriter::Write(*ConvertSearchSuggestDataToDict(data), &js);
js = "var searchSuggestions = " + js + ";"; js = "var searchSuggestions = " + js + ";";
result = base::RefCountedString::TakeString(&js); result = base::RefCountedString::TakeString(&js);
callback.Run(result); std::move(callback).Run(result);
} }
void LocalNtpSource::ServeOneGoogleBar( void LocalNtpSource::ServeOneGoogleBar(
@@ -1331,22 +1330,22 @@ void LocalNtpSource::ServeOneGoogleBar(
UMA_HISTOGRAM_MEDIUM_TIMES("NewTabPage.OneGoogleBar.RequestLatency.Failure", UMA_HISTOGRAM_MEDIUM_TIMES("NewTabPage.OneGoogleBar.RequestLatency.Failure",
delta); delta);
} }
for (const auto& callback : one_google_bar_callbacks_) { for (auto& callback : one_google_bar_callbacks_) {
callback.Run(result); std::move(callback).Run(result);
} }
pending_one_google_bar_request_ = base::nullopt; pending_one_google_bar_request_ = base::nullopt;
one_google_bar_callbacks_.clear(); one_google_bar_callbacks_.clear();
} }
void LocalNtpSource::ServeOneGoogleBarWhenAvailable( void LocalNtpSource::ServeOneGoogleBarWhenAvailable(
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
base::Optional<OneGoogleBarData> data = base::Optional<OneGoogleBarData> data =
one_google_bar_service_->one_google_bar_data(); one_google_bar_service_->one_google_bar_data();
if (!pending_one_google_bar_request_.has_value()) { if (!pending_one_google_bar_request_.has_value()) {
callback.Run(GetOGBString(data)); std::move(callback).Run(GetOGBString(data));
} else { } else {
one_google_bar_callbacks_.emplace_back(callback); one_google_bar_callbacks_.push_back(std::move(callback));
} }
} }
@@ -1376,21 +1375,21 @@ void LocalNtpSource::ServePromo(const base::Optional<PromoData>& data) {
UMA_HISTOGRAM_MEDIUM_TIMES("NewTabPage.Promos.RequestLatency2.Failure", UMA_HISTOGRAM_MEDIUM_TIMES("NewTabPage.Promos.RequestLatency2.Failure",
delta); delta);
} }
for (const auto& callback : promo_callbacks_) { for (auto& callback : promo_callbacks_) {
callback.Run(result); std::move(callback).Run(result);
} }
pending_promo_request_ = base::nullopt; pending_promo_request_ = base::nullopt;
promo_callbacks_.clear(); promo_callbacks_.clear();
} }
void LocalNtpSource::ServePromoWhenAvailable( void LocalNtpSource::ServePromoWhenAvailable(
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
base::Optional<PromoData> data = promo_service_->promo_data(); base::Optional<PromoData> data = promo_service_->promo_data();
if (!pending_promo_request_.has_value()) { if (!pending_promo_request_.has_value()) {
callback.Run(GetPromoString(data)); std::move(callback).Run(GetPromoString(data));
} else { } else {
promo_callbacks_.emplace_back(callback); promo_callbacks_.push_back(std::move(callback));
} }
} }
@@ -1407,10 +1406,12 @@ void LocalNtpSource::InitiatePromoAndOGBRequests() {
LocalNtpSource::NtpBackgroundRequest::NtpBackgroundRequest( LocalNtpSource::NtpBackgroundRequest::NtpBackgroundRequest(
base::TimeTicks start_time, base::TimeTicks start_time,
const content::URLDataSource::GotDataCallback& callback) content::URLDataSource::GotDataCallback callback)
: start_time(start_time), callback(callback) {} : start_time(start_time), callback(std::move(callback)) {}
LocalNtpSource::NtpBackgroundRequest::NtpBackgroundRequest( LocalNtpSource::NtpBackgroundRequest::NtpBackgroundRequest(
const NtpBackgroundRequest&) = default; NtpBackgroundRequest&&) = default;
LocalNtpSource::NtpBackgroundRequest& LocalNtpSource::NtpBackgroundRequest::
operator=(NtpBackgroundRequest&&) = default;
LocalNtpSource::NtpBackgroundRequest::~NtpBackgroundRequest() = default; LocalNtpSource::NtpBackgroundRequest::~NtpBackgroundRequest() = default;

@@ -59,10 +59,10 @@ class LocalNtpSource : public content::URLDataSource,
class DesktopLogoObserver; class DesktopLogoObserver;
struct NtpBackgroundRequest { struct NtpBackgroundRequest {
NtpBackgroundRequest( NtpBackgroundRequest(base::TimeTicks start_time,
base::TimeTicks start_time, content::URLDataSource::GotDataCallback callback);
const content::URLDataSource::GotDataCallback& callback); NtpBackgroundRequest(NtpBackgroundRequest&&);
NtpBackgroundRequest(const NtpBackgroundRequest&); NtpBackgroundRequest& operator=(NtpBackgroundRequest&&);
~NtpBackgroundRequest(); ~NtpBackgroundRequest();
base::TimeTicks start_time; base::TimeTicks start_time;
@@ -74,7 +74,7 @@ class LocalNtpSource : public content::URLDataSource,
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
bool AllowCaching() override; bool AllowCaching() override;
bool ShouldServiceRequest(const GURL& url, bool ShouldServiceRequest(const GURL& url,
@@ -110,7 +110,7 @@ class LocalNtpSource : public content::URLDataSource,
// is returned immediately, otherwise it is returned when it becomes available // is returned immediately, otherwise it is returned when it becomes available
// in ServeOneGoogleBar. // in ServeOneGoogleBar.
void ServeOneGoogleBarWhenAvailable( void ServeOneGoogleBarWhenAvailable(
const content::URLDataSource::GotDataCallback& callback); content::URLDataSource::GotDataCallback callback);
// Called when the promo data is available and serves |data| to any pending // Called when the promo data is available and serves |data| to any pending
// requests from the NTP. // requests from the NTP.
@@ -119,12 +119,12 @@ class LocalNtpSource : public content::URLDataSource,
// is returned immediately, otherwise it is returned when it becomes // is returned immediately, otherwise it is returned when it becomes
// available in ServePromo. // available in ServePromo.
void ServePromoWhenAvailable( void ServePromoWhenAvailable(
const content::URLDataSource::GotDataCallback& callback); content::URLDataSource::GotDataCallback callback);
// If suggestion data is available return it immediately, otherwise no search // If suggestion data is available return it immediately, otherwise no search
// suggestions will be shown on this NTP load. // suggestions will be shown on this NTP load.
void ServeSearchSuggestionsIfAvailable( void ServeSearchSuggestionsIfAvailable(
const content::URLDataSource::GotDataCallback& callback); content::URLDataSource::GotDataCallback callback);
// Start requests for the promo and OGB. // Start requests for the promo and OGB.
void InitiatePromoAndOGBRequests(); void InitiatePromoAndOGBRequests();

@@ -63,54 +63,55 @@ std::string MostVisitedIframeSource::GetSource() {
void MostVisitedIframeSource::StartDataRequest( void MostVisitedIframeSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available. // TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
const std::string path(url.path()); const std::string path(url.path());
if (path == kSingleHTMLPath) { if (path == kSingleHTMLPath) {
SendResource(IDR_MOST_VISITED_SINGLE_HTML, callback); SendResource(IDR_MOST_VISITED_SINGLE_HTML, std::move(callback));
} else if (path == kSingleCSSPath) { } else if (path == kSingleCSSPath) {
SendResource(IDR_MOST_VISITED_SINGLE_CSS, callback); SendResource(IDR_MOST_VISITED_SINGLE_CSS, std::move(callback));
} else if (path == kSingleJSPath) { } else if (path == kSingleJSPath) {
SendJSWithOrigin(IDR_MOST_VISITED_SINGLE_JS, wc_getter, callback); SendJSWithOrigin(IDR_MOST_VISITED_SINGLE_JS, wc_getter,
std::move(callback));
} else if (path == kTitleHTMLPath) { } else if (path == kTitleHTMLPath) {
SendResource(IDR_MOST_VISITED_TITLE_HTML, callback); SendResource(IDR_MOST_VISITED_TITLE_HTML, std::move(callback));
} else if (path == kTitleCSSPath) { } else if (path == kTitleCSSPath) {
SendResource(IDR_MOST_VISITED_TITLE_CSS, callback); SendResource(IDR_MOST_VISITED_TITLE_CSS, std::move(callback));
} else if (path == kTitleJSPath) { } else if (path == kTitleJSPath) {
SendResource(IDR_MOST_VISITED_TITLE_JS, callback); SendResource(IDR_MOST_VISITED_TITLE_JS, std::move(callback));
} else if (path == kUtilJSPath) { } else if (path == kUtilJSPath) {
SendJSWithOrigin(IDR_MOST_VISITED_UTIL_JS, wc_getter, callback); SendJSWithOrigin(IDR_MOST_VISITED_UTIL_JS, wc_getter, std::move(callback));
} else if (path == kCommonCSSPath) { } else if (path == kCommonCSSPath) {
SendResource(IDR_MOST_VISITED_IFRAME_CSS, callback); SendResource(IDR_MOST_VISITED_IFRAME_CSS, std::move(callback));
} else if (path == kDontShowPngPath) { } else if (path == kDontShowPngPath) {
SendResource(IDR_MOST_VISITED_DONT_SHOW_PNG, callback); SendResource(IDR_MOST_VISITED_DONT_SHOW_PNG, std::move(callback));
} else if (path == kDontShow2XPngPath) { } else if (path == kDontShow2XPngPath) {
SendResource(IDR_MOST_VISITED_DONT_SHOW_2X_PNG, callback); SendResource(IDR_MOST_VISITED_DONT_SHOW_2X_PNG, std::move(callback));
} else if (path == kEditHTMLPath) { } else if (path == kEditHTMLPath) {
SendResource(IDR_CUSTOM_LINKS_EDIT_HTML, callback); SendResource(IDR_CUSTOM_LINKS_EDIT_HTML, std::move(callback));
} else if (path == kEditCSSPath) { } else if (path == kEditCSSPath) {
SendResource(IDR_CUSTOM_LINKS_EDIT_CSS, callback); SendResource(IDR_CUSTOM_LINKS_EDIT_CSS, std::move(callback));
} else if (path == kEditJSPath) { } else if (path == kEditJSPath) {
SendJSWithOrigin(IDR_CUSTOM_LINKS_EDIT_JS, wc_getter, callback); SendJSWithOrigin(IDR_CUSTOM_LINKS_EDIT_JS, wc_getter, std::move(callback));
} else if (path == kAddSvgPath) { } else if (path == kAddSvgPath) {
SendResource(IDR_CUSTOM_LINKS_ADD_SVG, callback); SendResource(IDR_CUSTOM_LINKS_ADD_SVG, std::move(callback));
} else if (path == kAddWhiteSvgPath) { } else if (path == kAddWhiteSvgPath) {
SendResource(IDR_CUSTOM_LINKS_ADD_WHITE_SVG, callback); SendResource(IDR_CUSTOM_LINKS_ADD_WHITE_SVG, std::move(callback));
} else if (path == kEditMenuSvgPath) { } else if (path == kEditMenuSvgPath) {
SendResource(IDR_CUSTOM_LINKS_EDIT_MENU_SVG, callback); SendResource(IDR_CUSTOM_LINKS_EDIT_MENU_SVG, std::move(callback));
} else if (path == kLocalNTPCommonCSSPath) { } else if (path == kLocalNTPCommonCSSPath) {
SendResource(IDR_LOCAL_NTP_COMMON_CSS, callback); SendResource(IDR_LOCAL_NTP_COMMON_CSS, std::move(callback));
} else if (path == kAnimationsCSSPath) { } else if (path == kAnimationsCSSPath) {
SendResource(IDR_LOCAL_NTP_ANIMATIONS_CSS, callback); SendResource(IDR_LOCAL_NTP_ANIMATIONS_CSS, std::move(callback));
} else if (path == kAnimationsJSPath) { } else if (path == kAnimationsJSPath) {
SendResource(IDR_LOCAL_NTP_ANIMATIONS_JS, callback); SendResource(IDR_LOCAL_NTP_ANIMATIONS_JS, std::move(callback));
} else if (path == kLocalNTPUtilsJSPath) { } else if (path == kLocalNTPUtilsJSPath) {
SendResource(IDR_LOCAL_NTP_UTILS_JS, callback); SendResource(IDR_LOCAL_NTP_UTILS_JS, std::move(callback));
} else if (path == kAssertJsPath) { } else if (path == kAssertJsPath) {
SendResource(IDR_WEBUI_JS_ASSERT, callback); SendResource(IDR_WEBUI_JS_ASSERT, std::move(callback));
} else { } else {
callback.Run(nullptr); std::move(callback).Run(nullptr);
} }
} }
@@ -163,18 +164,19 @@ bool MostVisitedIframeSource::ServesPath(const std::string& path) const {
void MostVisitedIframeSource::SendResource( void MostVisitedIframeSource::SendResource(
int resource_id, int resource_id,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
callback.Run(ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes( std::move(callback).Run(
resource_id)); ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
resource_id));
} }
void MostVisitedIframeSource::SendJSWithOrigin( void MostVisitedIframeSource::SendJSWithOrigin(
int resource_id, int resource_id,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
std::string origin; std::string origin;
if (!GetOrigin(wc_getter, &origin)) { if (!GetOrigin(wc_getter, &origin)) {
callback.Run(nullptr); std::move(callback).Run(nullptr);
return; return;
} }
@@ -182,7 +184,7 @@ void MostVisitedIframeSource::SendJSWithOrigin(
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id); ui::ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);
std::string response(template_js.as_string()); std::string response(template_js.as_string());
base::ReplaceFirstSubstringAfterOffset(&response, 0, "{{ORIGIN}}", origin); base::ReplaceFirstSubstringAfterOffset(&response, 0, "{{ORIGIN}}", origin);
callback.Run(base::RefCountedString::TakeString(&response)); std::move(callback).Run(base::RefCountedString::TakeString(&response));
} }
bool MostVisitedIframeSource::GetOrigin( bool MostVisitedIframeSource::GetOrigin(

@@ -25,7 +25,7 @@ class MostVisitedIframeSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path_and_query) override; std::string GetMimeType(const std::string& path_and_query) override;
bool AllowCaching() override; bool AllowCaching() override;
bool ShouldDenyXFrameOptions() override; bool ShouldDenyXFrameOptions() override;
@@ -39,13 +39,12 @@ class MostVisitedIframeSource : public content::URLDataSource {
// Sends unmodified resource bytes. // Sends unmodified resource bytes.
void SendResource(int resource_id, void SendResource(int resource_id,
const content::URLDataSource::GotDataCallback& callback); content::URLDataSource::GotDataCallback callback);
// Sends Javascript with an expected postMessage origin interpolated. // Sends Javascript with an expected postMessage origin interpolated.
void SendJSWithOrigin( void SendJSWithOrigin(int resource_id,
int resource_id, const content::WebContents::Getter& wc_getter,
const content::WebContents::Getter& wc_getter, content::URLDataSource::GotDataCallback callback);
const content::URLDataSource::GotDataCallback& callback);
// This is exposed for testing and should not be overridden. // This is exposed for testing and should not be overridden.
// Sets |origin| to the URL of the WebContents identified by |wc_getter|. // Sets |origin| to the URL of the WebContents identified by |wc_getter|.

@@ -48,7 +48,7 @@ class TestMostVisitedIframeSource : public MostVisitedIframeSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override {} content::URLDataSource::GotDataCallback callback) override {}
// RenderFrameHost is hard to mock in concert with everything else, so stub // RenderFrameHost is hard to mock in concert with everything else, so stub
// this method out for testing. // this method out for testing.
@@ -85,12 +85,16 @@ class MostVisitedIframeSourceTest : public testing::Test {
} }
void SendResource(int resource_id) { void SendResource(int resource_id) {
source()->SendResource(resource_id, callback_); source()->SendResource(
resource_id, base::BindOnce(&MostVisitedIframeSourceTest::SaveResponse,
base::Unretained(this)));
} }
void SendJSWithOrigin(int resource_id) { void SendJSWithOrigin(int resource_id) {
source()->SendJSWithOrigin(resource_id, content::WebContents::Getter(), source()->SendJSWithOrigin(
callback_); resource_id, content::WebContents::Getter(),
base::BindOnce(&MostVisitedIframeSourceTest::SaveResponse,
base::Unretained(this)));
} }
bool ShouldService(const std::string& path, int process_id) { bool ShouldService(const std::string& path, int process_id) {
@@ -101,8 +105,6 @@ class MostVisitedIframeSourceTest : public testing::Test {
private: private:
void SetUp() override { void SetUp() override {
source_ = std::make_unique<TestMostVisitedIframeSource>(); source_ = std::make_unique<TestMostVisitedIframeSource>();
callback_ = base::Bind(&MostVisitedIframeSourceTest::SaveResponse,
base::Unretained(this));
instant_io_context_ = new InstantIOContext; instant_io_context_ = new InstantIOContext;
InstantIOContext::SetUserDataOnIO(&resource_context_, instant_io_context_); InstantIOContext::SetUserDataOnIO(&resource_context_, instant_io_context_);
source_->set_origin(kInstantOrigin); source_->set_origin(kInstantOrigin);
@@ -122,7 +124,6 @@ class MostVisitedIframeSourceTest : public testing::Test {
net::TestURLRequestContext test_url_request_context_; net::TestURLRequestContext test_url_request_context_;
content::MockResourceContext resource_context_; content::MockResourceContext resource_context_;
std::unique_ptr<TestMostVisitedIframeSource> source_; std::unique_ptr<TestMostVisitedIframeSource> source_;
content::URLDataSource::GotDataCallback callback_;
scoped_refptr<InstantIOContext> instant_io_context_; scoped_refptr<InstantIOContext> instant_io_context_;
scoped_refptr<base::RefCountedMemory> response_; scoped_refptr<base::RefCountedMemory> response_;
}; };

@@ -226,17 +226,20 @@ SkColor GetBackgroundColorForUrl(const GURL& icon_url) {
} // namespace } // namespace
struct NtpIconSource::NtpIconRequest { struct NtpIconSource::NtpIconRequest {
NtpIconRequest(const content::URLDataSource::GotDataCallback& cb, NtpIconRequest(content::URLDataSource::GotDataCallback cb,
const GURL& path, const GURL& path,
int icon_size_in_pixels, int icon_size_in_pixels,
float scale, float scale,
bool show_fallback_monogram) bool show_fallback_monogram)
: callback(cb), : callback(std::move(cb)),
path(path), path(path),
icon_size_in_pixels(icon_size_in_pixels), icon_size_in_pixels(icon_size_in_pixels),
device_scale_factor(scale), device_scale_factor(scale),
show_fallback_monogram(show_fallback_monogram) {} show_fallback_monogram(show_fallback_monogram) {}
NtpIconRequest(const NtpIconRequest& other) = default;
NtpIconRequest(NtpIconRequest&& other) = default;
NtpIconRequest& operator=(NtpIconRequest&& other) = default;
~NtpIconRequest() {} ~NtpIconRequest() {}
content::URLDataSource::GotDataCallback callback; content::URLDataSource::GotDataCallback callback;
@@ -262,7 +265,7 @@ std::string NtpIconSource::GetSource() {
void NtpIconSource::StartDataRequest( void NtpIconSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
favicon::FaviconService* favicon_service = favicon::FaviconService* favicon_service =
FaviconServiceFactory::GetForProfile(profile_, FaviconServiceFactory::GetForProfile(profile_,
ServiceAccessType::EXPLICIT_ACCESS); ServiceAccessType::EXPLICIT_ACCESS);
@@ -273,7 +276,7 @@ void NtpIconSource::StartDataRequest(
if (parsed.url.is_valid()) { if (parsed.url.is_valid()) {
int icon_size_in_pixels = int icon_size_in_pixels =
std::ceil(parsed.size_in_dip * parsed.device_scale_factor); std::ceil(parsed.size_in_dip * parsed.device_scale_factor);
NtpIconRequest request(callback, parsed.url, icon_size_in_pixels, NtpIconRequest request(std::move(callback), parsed.url, icon_size_in_pixels,
parsed.device_scale_factor, parsed.device_scale_factor,
parsed.show_fallback_monogram); parsed.show_fallback_monogram);
@@ -295,10 +298,10 @@ void NtpIconSource::StartDataRequest(
gfx::ImageSkiaOperations::CreateResizedImage( gfx::ImageSkiaOperations::CreateResizedImage(
image.AsImageSkia(), skia::ImageOperations::RESIZE_BEST, image.AsImageSkia(), skia::ImageOperations::RESIZE_BEST,
target_size); target_size);
ReturnRenderedIconForRequest(request, ReturnRenderedIconForRequest(std::move(request),
gfx::Image(resized_image).AsBitmap()); gfx::Image(resized_image).AsBitmap());
} else { } else {
ReturnRenderedIconForRequest(request, image.AsBitmap()); ReturnRenderedIconForRequest(std::move(request), image.AsBitmap());
} }
return; return;
} }
@@ -311,11 +314,11 @@ void NtpIconSource::StartDataRequest(
favicon_service->GetRawFaviconForPageURL( favicon_service->GetRawFaviconForPageURL(
parsed.url, {favicon_base::IconType::kFavicon}, icon_size_in_pixels, parsed.url, {favicon_base::IconType::kFavicon}, icon_size_in_pixels,
fallback_to_host, fallback_to_host,
base::Bind(&NtpIconSource::OnLocalFaviconAvailable, base::BindOnce(&NtpIconSource::OnLocalFaviconAvailable,
weak_ptr_factory_.GetWeakPtr(), request), weak_ptr_factory_.GetWeakPtr(), std::move(request)),
&cancelable_task_tracker_); &cancelable_task_tracker_);
} else { } else {
callback.Run(nullptr); std::move(callback).Run(nullptr);
} }
} }
@@ -338,7 +341,7 @@ bool NtpIconSource::ShouldServiceRequest(
} }
void NtpIconSource::OnLocalFaviconAvailable( void NtpIconSource::OnLocalFaviconAvailable(
const NtpIconRequest& request, NtpIconRequest request,
const favicon_base::FaviconRawBitmapResult& bitmap_result) { const favicon_base::FaviconRawBitmapResult& bitmap_result) {
if (bitmap_result.is_valid()) { if (bitmap_result.is_valid()) {
// A local favicon was found. Decode it to an SkBitmap so it can eventually // A local favicon was found. Decode it to an SkBitmap so it can eventually
@@ -348,12 +351,12 @@ void NtpIconSource::OnLocalFaviconAvailable(
gfx::PNGCodec::Decode(bitmap_result.bitmap_data.get()->front(), gfx::PNGCodec::Decode(bitmap_result.bitmap_data.get()->front(),
bitmap_result.bitmap_data.get()->size(), &bitmap); bitmap_result.bitmap_data.get()->size(), &bitmap);
DCHECK(result); DCHECK(result);
ReturnRenderedIconForRequest(request, bitmap); ReturnRenderedIconForRequest(std::move(request), bitmap);
} else { } else {
// Since a local favicon was not found, attempt to fetch a server icon if // Since a local favicon was not found, attempt to fetch a server icon if
// the url is known to the server (this last check is important to avoid // the url is known to the server (this last check is important to avoid
// leaking private history to the server). // leaking private history to the server).
RequestServerFavicon(request); RequestServerFavicon(std::move(request));
} }
} }
@@ -374,14 +377,14 @@ bool NtpIconSource::IsRequestedUrlInServerSuggestions(const GURL& url) {
return position != profile.suggestions().end(); return position != profile.suggestions().end();
} }
void NtpIconSource::RequestServerFavicon(const NtpIconRequest& request) { void NtpIconSource::RequestServerFavicon(NtpIconRequest request) {
// Only fetch a server icon if the page url is known to the server. This check // Only fetch a server icon if the page url is known to the server. This check
// is important to avoid leaking private history to the server. // is important to avoid leaking private history to the server.
const GURL server_favicon_url = const GURL server_favicon_url =
GURL(base::StringPrintf(kServerFaviconURL, request.path.spec().c_str())); GURL(base::StringPrintf(kServerFaviconURL, request.path.spec().c_str()));
if (!server_favicon_url.is_valid() || if (!server_favicon_url.is_valid() ||
!IsRequestedUrlInServerSuggestions(request.path)) { !IsRequestedUrlInServerSuggestions(request.path)) {
ReturnRenderedIconForRequest(request, SkBitmap()); ReturnRenderedIconForRequest(std::move(request), SkBitmap());
return; return;
} }
@@ -412,13 +415,13 @@ void NtpIconSource::RequestServerFavicon(const NtpIconRequest& request) {
gfx::Size(request.icon_size_in_pixels, request.icon_size_in_pixels)); gfx::Size(request.icon_size_in_pixels, request.icon_size_in_pixels));
image_fetcher_->FetchImage( image_fetcher_->FetchImage(
server_favicon_url, server_favicon_url,
base::Bind(&NtpIconSource::OnServerFaviconAvailable, base::BindOnce(&NtpIconSource::OnServerFaviconAvailable,
weak_ptr_factory_.GetWeakPtr(), request), weak_ptr_factory_.GetWeakPtr(), std::move(request)),
std::move(params)); std::move(params));
} }
void NtpIconSource::OnServerFaviconAvailable( void NtpIconSource::OnServerFaviconAvailable(
const NtpIconRequest& request, NtpIconRequest request,
const gfx::Image& fetched_image, const gfx::Image& fetched_image,
const image_fetcher::RequestMetadata& metadata) { const image_fetcher::RequestMetadata& metadata) {
// If a server icon was not found, |fetched_bitmap| will be empty and a // If a server icon was not found, |fetched_bitmap| will be empty and a
@@ -432,10 +435,10 @@ void NtpIconSource::OnServerFaviconAvailable(
request.icon_size_in_pixels, request.icon_size_in_pixels); request.icon_size_in_pixels, request.icon_size_in_pixels);
} }
ReturnRenderedIconForRequest(request, fetched_bitmap); ReturnRenderedIconForRequest(std::move(request), fetched_bitmap);
} }
void NtpIconSource::ReturnRenderedIconForRequest(const NtpIconRequest& request, void NtpIconSource::ReturnRenderedIconForRequest(NtpIconRequest request,
const SkBitmap& favicon) { const SkBitmap& favicon) {
// Only use even pixel sizes to avoid issues when centering the fallback // Only use even pixel sizes to avoid issues when centering the fallback
// monogram. // monogram.
@@ -478,5 +481,6 @@ void NtpIconSource::ReturnRenderedIconForRequest(const NtpIconRequest& request,
std::vector<unsigned char> bitmap_data; std::vector<unsigned char> bitmap_data;
bool result = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &bitmap_data); bool result = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &bitmap_data);
DCHECK(result); DCHECK(result);
request.callback.Run(base::RefCountedBytes::TakeVector(&bitmap_data)); std::move(request.callback)
.Run(base::RefCountedBytes::TakeVector(&bitmap_data));
} }

@@ -39,7 +39,7 @@ class NtpIconSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
bool ShouldServiceRequest(const GURL& url, bool ShouldServiceRequest(const GURL& url,
content::ResourceContext* resource_context, content::ResourceContext* resource_context,
@@ -48,19 +48,19 @@ class NtpIconSource : public content::URLDataSource {
private: private:
struct NtpIconRequest; struct NtpIconRequest;
void OnLocalFaviconAvailable( void OnLocalFaviconAvailable(
const NtpIconRequest& request, NtpIconRequest request,
const favicon_base::FaviconRawBitmapResult& bitmap_result); const favicon_base::FaviconRawBitmapResult& bitmap_result);
// Returns whether |url| is in the set of server suggestions. // Returns whether |url| is in the set of server suggestions.
bool IsRequestedUrlInServerSuggestions(const GURL& url); bool IsRequestedUrlInServerSuggestions(const GURL& url);
void RequestServerFavicon(const NtpIconRequest& request); void RequestServerFavicon(NtpIconRequest request);
void OnServerFaviconAvailable(const NtpIconRequest& request, void OnServerFaviconAvailable(NtpIconRequest request,
const gfx::Image& fetched_image, const gfx::Image& fetched_image,
const image_fetcher::RequestMetadata& metadata); const image_fetcher::RequestMetadata& metadata);
// Will call |request.callback| with the rendered icon. |bitmap| can be empty, // Will call |request.callback| with the rendered icon. |bitmap| can be empty,
// in which case the returned icon is a fallback circle with a letter drawn // in which case the returned icon is a fallback circle with a letter drawn
// into it. // into it.
void ReturnRenderedIconForRequest(const NtpIconRequest& request, void ReturnRenderedIconForRequest(NtpIconRequest request,
const SkBitmap& bitmap); const SkBitmap& bitmap);
base::CancelableTaskTracker cancelable_task_tracker_; base::CancelableTaskTracker cancelable_task_tracker_;

@@ -29,7 +29,7 @@ class SuggestionsSourceWrapper : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
private: private:
@@ -52,9 +52,9 @@ std::string SuggestionsSourceWrapper::GetSource() {
void SuggestionsSourceWrapper::StartDataRequest( void SuggestionsSourceWrapper::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
suggestions_source_.StartDataRequest( suggestions_source_.StartDataRequest(
content::URLDataSource::URLToRequestPath(url), callback); content::URLDataSource::URLToRequestPath(url), std::move(callback));
} }
std::string SuggestionsSourceWrapper::GetMimeType(const std::string& path) { std::string SuggestionsSourceWrapper::GetMimeType(const std::string& path) {

@@ -85,7 +85,7 @@ class FakeInstanceID : public instance_id::InstanceID {
void ValidateToken(const std::string& authorized_entity, void ValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) override { ValidateTokenCallback callback) override {
NOTIMPLEMENTED(); NOTIMPLEMENTED();
} }

@@ -113,7 +113,7 @@ class SyncTest : public InProcessBrowserTest {
void ValidateToken(const std::string& authorized_entity, void ValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) override {} ValidateTokenCallback callback) override {}
void DeleteToken(const std::string& authorized_entity, void DeleteToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,

@@ -184,9 +184,10 @@ void SetManifestRequestFilter(content::WebUIDataSource* source,
[](const std::string& path) { return path == "manifest.json"; }), [](const std::string& path) { return path == "manifest.json"; }),
base::BindRepeating( base::BindRepeating(
[](const std::string& response, const std::string& path, [](const std::string& response, const std::string& path,
const content::WebUIDataSource::GotDataCallback& callback) { content::WebUIDataSource::GotDataCallback callback) {
std::string response_copy = response; std::string response_copy = response;
callback.Run(base::RefCountedString::TakeString(&response_copy)); std::move(callback).Run(
base::RefCountedString::TakeString(&response_copy));
}, },
std::move(response))); std::move(response)));
} }

@@ -181,9 +181,9 @@ class ChromeOSTermsHandler
: public base::RefCountedThreadSafe<ChromeOSTermsHandler> { : public base::RefCountedThreadSafe<ChromeOSTermsHandler> {
public: public:
static void Start(const std::string& path, static void Start(const std::string& path,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
scoped_refptr<ChromeOSTermsHandler> handler( scoped_refptr<ChromeOSTermsHandler> handler(
new ChromeOSTermsHandler(path, callback)); new ChromeOSTermsHandler(path, std::move(callback)));
handler->StartOnUIThread(); handler->StartOnUIThread();
} }
@@ -191,9 +191,9 @@ class ChromeOSTermsHandler
friend class base::RefCountedThreadSafe<ChromeOSTermsHandler>; friend class base::RefCountedThreadSafe<ChromeOSTermsHandler>;
ChromeOSTermsHandler(const std::string& path, ChromeOSTermsHandler(const std::string& path,
const content::URLDataSource::GotDataCallback& callback) content::URLDataSource::GotDataCallback callback)
: path_(path), : path_(path),
callback_(callback), callback_(std::move(callback)),
// Previously we were using "initial locale" http://crbug.com/145142 // Previously we were using "initial locale" http://crbug.com/145142
locale_(g_browser_process->GetApplicationLocale()) {} locale_(g_browser_process->GetApplicationLocale()) {}
@@ -343,7 +343,7 @@ class ChromeOSTermsHandler
// Do nothing if OEM EULA or Play Store ToS load failed. // Do nothing if OEM EULA or Play Store ToS load failed.
if (contents_.empty() && path_.empty()) if (contents_.empty() && path_.empty())
contents_ = l10n_util::GetStringUTF8(IDS_TERMS_HTML); contents_ = l10n_util::GetStringUTF8(IDS_TERMS_HTML);
callback_.Run(base::RefCountedString::TakeString(&contents_)); std::move(callback_).Run(base::RefCountedString::TakeString(&contents_));
} }
// Path in the URL. // Path in the URL.
@@ -365,19 +365,18 @@ class ChromeOSCreditsHandler
: public base::RefCountedThreadSafe<ChromeOSCreditsHandler> { : public base::RefCountedThreadSafe<ChromeOSCreditsHandler> {
public: public:
static void Start(const std::string& path, static void Start(const std::string& path,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
scoped_refptr<ChromeOSCreditsHandler> handler( scoped_refptr<ChromeOSCreditsHandler> handler(
new ChromeOSCreditsHandler(path, callback)); new ChromeOSCreditsHandler(path, std::move(callback)));
handler->StartOnUIThread(); handler->StartOnUIThread();
} }
private: private:
friend class base::RefCountedThreadSafe<ChromeOSCreditsHandler>; friend class base::RefCountedThreadSafe<ChromeOSCreditsHandler>;
ChromeOSCreditsHandler( ChromeOSCreditsHandler(const std::string& path,
const std::string& path, content::URLDataSource::GotDataCallback callback)
const content::URLDataSource::GotDataCallback& callback) : path_(path), callback_(std::move(callback)) {}
: path_(path), callback_(callback) {}
virtual ~ChromeOSCreditsHandler() {} virtual ~ChromeOSCreditsHandler() {}
@@ -415,7 +414,7 @@ class ChromeOSCreditsHandler
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString( ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_OS_CREDITS_HTML); IDR_OS_CREDITS_HTML);
} }
callback_.Run(base::RefCountedString::TakeString(&contents_)); std::move(callback_).Run(base::RefCountedString::TakeString(&contents_));
} }
// Path in the URL. // Path in the URL.
@@ -434,9 +433,9 @@ class LinuxCreditsHandler
: public base::RefCountedThreadSafe<LinuxCreditsHandler> { : public base::RefCountedThreadSafe<LinuxCreditsHandler> {
public: public:
static void Start(const std::string& path, static void Start(const std::string& path,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
scoped_refptr<LinuxCreditsHandler> handler( scoped_refptr<LinuxCreditsHandler> handler(
new LinuxCreditsHandler(path, callback)); new LinuxCreditsHandler(path, std::move(callback)));
handler->StartOnUIThread(); handler->StartOnUIThread();
} }
@@ -444,8 +443,8 @@ class LinuxCreditsHandler
friend class base::RefCountedThreadSafe<LinuxCreditsHandler>; friend class base::RefCountedThreadSafe<LinuxCreditsHandler>;
LinuxCreditsHandler(const std::string& path, LinuxCreditsHandler(const std::string& path,
const content::URLDataSource::GotDataCallback& callback) content::URLDataSource::GotDataCallback callback)
: path_(path), callback_(callback) {} : path_(path), callback_(std::move(callback)) {}
virtual ~LinuxCreditsHandler() {} virtual ~LinuxCreditsHandler() {}
@@ -485,7 +484,7 @@ class LinuxCreditsHandler
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString( ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_OS_CREDITS_HTML); IDR_OS_CREDITS_HTML);
} }
callback_.Run(base::RefCountedString::TakeString(&contents_)); std::move(callback_).Run(base::RefCountedString::TakeString(&contents_));
} }
// Path in the URL. // Path in the URL.
@@ -597,7 +596,7 @@ std::string AboutUIHTMLSource::GetSource() {
void AboutUIHTMLSource::StartDataRequest( void AboutUIHTMLSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available. // TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
std::string response; std::string response;
@@ -624,16 +623,16 @@ void AboutUIHTMLSource::StartDataRequest(
#endif #endif
#if defined(OS_CHROMEOS) #if defined(OS_CHROMEOS)
} else if (source_name_ == chrome::kChromeUIOSCreditsHost) { } else if (source_name_ == chrome::kChromeUIOSCreditsHost) {
ChromeOSCreditsHandler::Start(path, callback); ChromeOSCreditsHandler::Start(path, std::move(callback));
return; return;
} else if (source_name_ == chrome::kChromeUILinuxCreditsHost) { } else if (source_name_ == chrome::kChromeUILinuxCreditsHost) {
LinuxCreditsHandler::Start(path, callback); LinuxCreditsHandler::Start(path, std::move(callback));
return; return;
#endif #endif
#if !defined(OS_ANDROID) #if !defined(OS_ANDROID)
} else if (source_name_ == chrome::kChromeUITermsHost) { } else if (source_name_ == chrome::kChromeUITermsHost) {
#if defined(OS_CHROMEOS) #if defined(OS_CHROMEOS)
ChromeOSTermsHandler::Start(path, callback); ChromeOSTermsHandler::Start(path, std::move(callback));
return; return;
#else #else
response = l10n_util::GetStringUTF8(IDS_TERMS_HTML); response = l10n_util::GetStringUTF8(IDS_TERMS_HTML);
@@ -641,14 +640,14 @@ void AboutUIHTMLSource::StartDataRequest(
#endif #endif
} }
FinishDataRequest(response, callback); FinishDataRequest(response, std::move(callback));
} }
void AboutUIHTMLSource::FinishDataRequest( void AboutUIHTMLSource::FinishDataRequest(
const std::string& html, const std::string& html,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
std::string html_copy(html); std::string html_copy(html);
callback.Run(base::RefCountedString::TakeString(&html_copy)); std::move(callback).Run(base::RefCountedString::TakeString(&html_copy));
} }
std::string AboutUIHTMLSource::GetMimeType(const std::string& path) { std::string AboutUIHTMLSource::GetMimeType(const std::string& path) {

@@ -27,16 +27,15 @@ class AboutUIHTMLSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
bool ShouldAddContentSecurityPolicy() override; bool ShouldAddContentSecurityPolicy() override;
std::string GetAccessControlAllowOriginForOrigin( std::string GetAccessControlAllowOriginForOrigin(
const std::string& origin) override; const std::string& origin) override;
// Send the response data. // Send the response data.
void FinishDataRequest( void FinishDataRequest(const std::string& html,
const std::string& html, content::URLDataSource::GotDataCallback callback);
const content::URLDataSource::GotDataCallback& callback);
Profile* profile() { return profile_; } Profile* profile() { return profile_; }

@@ -101,7 +101,7 @@ std::string AppLauncherPageUI::HTMLSource::GetSource() {
void AppLauncherPageUI::HTMLSource::StartDataRequest( void AppLauncherPageUI::HTMLSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
NTPResourceCache* resource = AppResourceCacheFactory::GetForProfile(profile_); NTPResourceCache* resource = AppResourceCacheFactory::GetForProfile(profile_);
@@ -114,7 +114,7 @@ void AppLauncherPageUI::HTMLSource::StartDataRequest(
scoped_refptr<base::RefCountedMemory> html_bytes( scoped_refptr<base::RefCountedMemory> html_bytes(
resource->GetNewTabHTML(win_type)); resource->GetNewTabHTML(win_type));
callback.Run(html_bytes.get()); std::move(callback).Run(html_bytes.get());
} }
std::string AppLauncherPageUI::HTMLSource::GetMimeType( std::string AppLauncherPageUI::HTMLSource::GetMimeType(

@@ -41,7 +41,7 @@ class AppLauncherPageUI : public content::WebUIController {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string&) override; std::string GetMimeType(const std::string&) override;
bool ShouldReplaceExistingSource() override; bool ShouldReplaceExistingSource() override;
bool AllowCaching() override; bool AllowCaching() override;

@@ -112,12 +112,11 @@ base::string16 GetActivationErrorMessage(MobileActivator::ActivationError error,
MobileActivator::ActivationError::kActivationFailed, carrier); MobileActivator::ActivationError::kActivationFailed, carrier);
} }
void DataRequestFailed( void DataRequestFailed(const std::string& service_path,
const std::string& service_path, content::URLDataSource::GotDataCallback callback) {
const content::URLDataSource::GotDataCallback& callback) {
NET_LOG(ERROR) << "Data Request Failed for Mobile Setup: " << service_path; NET_LOG(ERROR) << "Data Request Failed for Mobile Setup: " << service_path;
scoped_refptr<base::RefCountedBytes> html_bytes(new base::RefCountedBytes); scoped_refptr<base::RefCountedBytes> html_bytes(new base::RefCountedBytes);
callback.Run(html_bytes.get()); std::move(callback).Run(html_bytes.get());
} }
// Keys for the dictionary that is set to activation UI and that contains the // Keys for the dictionary that is set to activation UI and that contains the
@@ -179,7 +178,7 @@ class MobileSetupUIHTMLSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string&) override { return "text/html"; } std::string GetMimeType(const std::string&) override { return "text/html"; }
bool ShouldAddContentSecurityPolicy() override { return false; } bool ShouldAddContentSecurityPolicy() override { return false; }
bool AllowCaching() override { bool AllowCaching() override {
@@ -271,7 +270,7 @@ std::string MobileSetupUIHTMLSource::GetSource() {
void MobileSetupUIHTMLSource::StartDataRequest( void MobileSetupUIHTMLSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
// Sanity checks that activation was requested for an appropriate network. // Sanity checks that activation was requested for an appropriate network.
const NetworkState* network = const NetworkState* network =
@@ -279,13 +278,13 @@ void MobileSetupUIHTMLSource::StartDataRequest(
if (!network) { if (!network) {
NET_LOG(ERROR) << "Network for mobile setup not found: " << path; NET_LOG(ERROR) << "Network for mobile setup not found: " << path;
DataRequestFailed(path, callback); DataRequestFailed(path, std::move(callback));
return; return;
} }
if (!network->Matches(NetworkTypePattern::Cellular())) { if (!network->Matches(NetworkTypePattern::Cellular())) {
NET_LOG(ERROR) << "Mobile setup attempt for non cellular network: " << path; NET_LOG(ERROR) << "Mobile setup attempt for non cellular network: " << path;
DataRequestFailed(path, callback); DataRequestFailed(path, std::move(callback));
return; return;
} }
@@ -294,7 +293,7 @@ void MobileSetupUIHTMLSource::StartDataRequest(
NET_LOG(ERROR) << "Mobile setup network in unexpected state: " << path NET_LOG(ERROR) << "Mobile setup network in unexpected state: " << path
<< " payment_url: " << network->payment_url() << " payment_url: " << network->payment_url()
<< " activation_state: " << network->activation_state(); << " activation_state: " << network->activation_state();
DataRequestFailed(path, callback); DataRequestFailed(path, std::move(callback));
return; return;
} }
@@ -304,7 +303,7 @@ void MobileSetupUIHTMLSource::StartDataRequest(
if (!device) { if (!device) {
NET_LOG(ERROR) << "Network device for mobile setup not found: " NET_LOG(ERROR) << "Network device for mobile setup not found: "
<< network->device_path(); << network->device_path();
DataRequestFailed(path, callback); DataRequestFailed(path, std::move(callback));
return; return;
} }
@@ -354,7 +353,7 @@ void MobileSetupUIHTMLSource::StartDataRequest(
full_html = webui::GetI18nTemplateHtml(html_for_non_activated, &strings); full_html = webui::GetI18nTemplateHtml(html_for_non_activated, &strings);
} }
callback.Run(base::RefCountedString::TakeString(&full_html)); std::move(callback).Run(base::RefCountedString::TakeString(&full_html));
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////

@@ -29,13 +29,12 @@ namespace {
const char* const kWhitelistedDirectories[] = {"regulatory_labels"}; const char* const kWhitelistedDirectories[] = {"regulatory_labels"};
// Callback for user_manager::UserImageLoader. // Callback for user_manager::UserImageLoader.
void ImageLoaded( void ImageLoaded(content::URLDataSource::GotDataCallback got_data_callback,
const content::URLDataSource::GotDataCallback& got_data_callback, std::unique_ptr<user_manager::UserImage> user_image) {
std::unique_ptr<user_manager::UserImage> user_image) {
if (user_image->has_image_bytes()) if (user_image->has_image_bytes())
got_data_callback.Run(user_image->image_bytes()); std::move(got_data_callback).Run(user_image->image_bytes());
else else
got_data_callback.Run(nullptr); std::move(got_data_callback).Run(nullptr);
} }
} // namespace } // namespace
@@ -56,10 +55,10 @@ std::string ImageSource::GetSource() {
void ImageSource::StartDataRequest( void ImageSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& got_data_callback) { content::URLDataSource::GotDataCallback got_data_callback) {
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
if (!IsWhitelisted(path)) { if (!IsWhitelisted(path)) {
got_data_callback.Run(nullptr); std::move(got_data_callback).Run(nullptr);
return; return;
} }
@@ -68,24 +67,23 @@ void ImageSource::StartDataRequest(
base::PostTaskAndReplyWithResult( base::PostTaskAndReplyWithResult(
FROM_HERE, FROM_HERE,
{base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::Bind(&base::PathExists, image_path), base::BindOnce(&base::PathExists, image_path),
base::Bind(&ImageSource::StartDataRequestAfterPathExists, base::BindOnce(&ImageSource::StartDataRequestAfterPathExists,
weak_factory_.GetWeakPtr(), image_path, got_data_callback)); weak_factory_.GetWeakPtr(), image_path,
std::move(got_data_callback)));
} }
void ImageSource::StartDataRequestAfterPathExists( void ImageSource::StartDataRequestAfterPathExists(
const base::FilePath& image_path, const base::FilePath& image_path,
const content::URLDataSource::GotDataCallback& got_data_callback, content::URLDataSource::GotDataCallback got_data_callback,
bool path_exists) { bool path_exists) {
if (path_exists) { if (path_exists) {
user_image_loader::StartWithFilePath( user_image_loader::StartWithFilePath(
task_runner_, task_runner_, image_path, ImageDecoder::DEFAULT_CODEC,
image_path,
ImageDecoder::DEFAULT_CODEC,
0, // Do not crop. 0, // Do not crop.
base::Bind(&ImageLoaded, got_data_callback)); base::BindOnce(&ImageLoaded, std::move(got_data_callback)));
} else { } else {
got_data_callback.Run(nullptr); std::move(got_data_callback).Run(nullptr);
} }
} }

@@ -27,10 +27,10 @@ class ImageSource : public content::URLDataSource {
// content::URLDataSource implementation. // content::URLDataSource implementation.
std::string GetSource() override; std::string GetSource() override;
void StartDataRequest(const GURL& url, void StartDataRequest(
const content::WebContents::Getter& wc_getter, const GURL& url,
const content::URLDataSource::GotDataCallback& const content::WebContents::Getter& wc_getter,
got_data_callback) override; content::URLDataSource::GotDataCallback got_data_callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
@@ -38,7 +38,7 @@ class ImageSource : public content::URLDataSource {
// Continuation from StartDataRequest(). // Continuation from StartDataRequest().
void StartDataRequestAfterPathExists( void StartDataRequestAfterPathExists(
const base::FilePath& image_path, const base::FilePath& image_path,
const content::URLDataSource::GotDataCallback& got_data_callback, content::URLDataSource::GotDataCallback got_data_callback,
bool path_exists); bool path_exists);
// Checks whether we have allowed the image to be loaded. // Checks whether we have allowed the image to be loaded.

@@ -36,9 +36,9 @@ std::string ScreenlockIconSource::GetSource() const {
void ScreenlockIconSource::StartDataRequest( void ScreenlockIconSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
if (!icon_provider_) { if (!icon_provider_) {
callback.Run(GetDefaultIcon().As1xPNGBytes().get()); std::move(callback).Run(GetDefaultIcon().As1xPNGBytes().get());
return; return;
} }
@@ -49,11 +49,11 @@ void ScreenlockIconSource::StartDataRequest(
gfx::Image image = icon_provider_->GetIcon(username); gfx::Image image = icon_provider_->GetIcon(username);
if (image.IsEmpty()) { if (image.IsEmpty()) {
callback.Run(GetDefaultIcon().As1xPNGBytes().get()); std::move(callback).Run(GetDefaultIcon().As1xPNGBytes().get());
return; return;
} }
callback.Run(image.As1xPNGBytes().get()); std::move(callback).Run(image.As1xPNGBytes().get());
} }
std::string ScreenlockIconSource::GetMimeType(const std::string&) const { std::string ScreenlockIconSource::GetMimeType(const std::string&) const {

@@ -25,7 +25,7 @@ class ScreenlockIconSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) const override; std::string GetMimeType(const std::string& path) const override;

@@ -35,7 +35,7 @@ std::string SlowTraceSource::GetSource() {
void SlowTraceSource::StartDataRequest( void SlowTraceSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
int trace_id = 0; int trace_id = 0;
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available. // TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
@@ -44,13 +44,12 @@ void SlowTraceSource::StartDataRequest(
if (!manager || if (!manager ||
pos == std::string::npos || pos == std::string::npos ||
!base::StringToInt(path.substr(pos + 1), &trace_id)) { !base::StringToInt(path.substr(pos + 1), &trace_id)) {
callback.Run(nullptr); std::move(callback).Run(nullptr);
return; return;
} }
manager->GetTraceData(trace_id, manager->GetTraceData(
base::Bind(&SlowTraceSource::OnGetTraceData, trace_id, base::BindOnce(&SlowTraceSource::OnGetTraceData,
base::Unretained(this), base::Unretained(this), std::move(callback)));
callback));
} }
std::string SlowTraceSource::GetMimeType(const std::string& path) { std::string SlowTraceSource::GetMimeType(const std::string& path) {
@@ -60,9 +59,9 @@ std::string SlowTraceSource::GetMimeType(const std::string& path) {
SlowTraceSource::~SlowTraceSource() {} SlowTraceSource::~SlowTraceSource() {}
void SlowTraceSource::OnGetTraceData( void SlowTraceSource::OnGetTraceData(
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
scoped_refptr<base::RefCountedString> trace_data) { scoped_refptr<base::RefCountedString> trace_data) {
callback.Run(trace_data.get()); std::move(callback).Run(trace_data.get());
} }
bool SlowTraceSource::AllowCaching() { bool SlowTraceSource::AllowCaching() {

@@ -33,12 +33,12 @@ class SlowTraceSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
bool AllowCaching() override; bool AllowCaching() override;
private: private:
void OnGetTraceData(const content::URLDataSource::GotDataCallback& callback, void OnGetTraceData(content::URLDataSource::GotDataCallback callback,
scoped_refptr<base::RefCountedString> trace_data); scoped_refptr<base::RefCountedString> trace_data);
DISALLOW_COPY_AND_ASSIGN(SlowTraceSource); DISALLOW_COPY_AND_ASSIGN(SlowTraceSource);

@@ -25,7 +25,7 @@ constexpr base::FilePath::CharType kDefaultFile[] =
constexpr char kDefaultMime[] = "text/html"; constexpr char kDefaultMime[] = "text/html";
void ReadFile(const base::FilePath& path, void ReadFile(const base::FilePath& path,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
std::string content; std::string content;
// First look for uncompressed resource, then try for gzipped file. // First look for uncompressed resource, then try for gzipped file.
bool result = base::ReadFileToString(path, &content); bool result = base::ReadFileToString(path, &content);
@@ -43,7 +43,7 @@ void ReadFile(const base::FilePath& path,
<< path; << path;
scoped_refptr<base::RefCountedString> response = scoped_refptr<base::RefCountedString> response =
base::RefCountedString::TakeString(&content); base::RefCountedString::TakeString(&content);
callback.Run(response.get()); std::move(callback).Run(response.get());
} }
} // namespace } // namespace
@@ -60,7 +60,7 @@ bool TerminalSource::AllowCaching() {
void TerminalSource::StartDataRequest( void TerminalSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available. // TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
// Reparse path to strip any query or fragment, skip first '/' in path. // Reparse path to strip any query or fragment, skip first '/' in path.
@@ -72,7 +72,7 @@ void TerminalSource::StartDataRequest(
base::PostTask( base::PostTask(
FROM_HERE, FROM_HERE,
{base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING},
base::BindOnce(&ReadFile, file_path, callback)); base::BindOnce(&ReadFile, file_path, std::move(callback)));
} }
std::string TerminalSource::GetMimeType(const std::string& path) { std::string TerminalSource::GetMimeType(const std::string& path) {

@@ -27,7 +27,7 @@ class TerminalSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;

@@ -180,7 +180,7 @@ std::string UserImageSource::GetSource() {
void UserImageSource::StartDataRequest( void UserImageSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
// TODO(crbug/1009127): Make sure |url| matches // TODO(crbug/1009127): Make sure |url| matches
// |chrome::kChromeUIUserImageURL| now that |url| is available. // |chrome::kChromeUIUserImageURL| now that |url| is available.
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
@@ -188,7 +188,7 @@ void UserImageSource::StartDataRequest(
int frame = -1; int frame = -1;
ParseRequest(url, &email, &frame); ParseRequest(url, &email, &frame);
const AccountId account_id(AccountId::FromUserEmail(email)); const AccountId account_id(AccountId::FromUserEmail(email));
callback.Run(GetUserImageInternal(account_id, frame)); std::move(callback).Run(GetUserImageInternal(account_id, frame));
} }
std::string UserImageSource::GetMimeType(const std::string& path) { std::string UserImageSource::GetMimeType(const std::string& path) {

@@ -34,7 +34,7 @@ class UserImageSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
// Returns PNG encoded image for user with specified |account_id|. If there's // Returns PNG encoded image for user with specified |account_id|. If there's

@@ -39,16 +39,16 @@ bool IsWhitelisted(const std::string& path) {
} }
// Callback for user_manager::UserImageLoader. // Callback for user_manager::UserImageLoader.
void VideoLoaded( void VideoLoaded(content::URLDataSource::GotDataCallback got_data_callback,
const content::URLDataSource::GotDataCallback& got_data_callback, std::unique_ptr<std::string> video_data,
std::unique_ptr<std::string> video_data, bool did_load_file) {
bool did_load_file) {
if (video_data->size() && did_load_file) { if (video_data->size() && did_load_file) {
got_data_callback.Run(new base::RefCountedBytes( std::move(got_data_callback)
reinterpret_cast<const unsigned char*>(video_data->data()), .Run(new base::RefCountedBytes(
video_data->size())); reinterpret_cast<const unsigned char*>(video_data->data()),
video_data->size()));
} else { } else {
got_data_callback.Run(nullptr); std::move(got_data_callback).Run(nullptr);
} }
} }
@@ -69,10 +69,10 @@ std::string VideoSource::GetSource() {
void VideoSource::StartDataRequest( void VideoSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& got_data_callback) { content::URLDataSource::GotDataCallback got_data_callback) {
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
if (!IsWhitelisted(path)) { if (!IsWhitelisted(path)) {
got_data_callback.Run(nullptr); std::move(got_data_callback).Run(nullptr);
return; return;
} }
@@ -84,7 +84,7 @@ void VideoSource::StartDataRequest(
base::BindOnce(&base::PathExists, video_path), base::BindOnce(&base::PathExists, video_path),
base::BindOnce(&VideoSource::StartDataRequestAfterPathExists, base::BindOnce(&VideoSource::StartDataRequestAfterPathExists,
weak_factory_.GetWeakPtr(), video_path, weak_factory_.GetWeakPtr(), video_path,
got_data_callback)); std::move(got_data_callback)));
} }
std::string VideoSource::GetMimeType(const std::string& path) { std::string VideoSource::GetMimeType(const std::string& path) {
@@ -97,7 +97,7 @@ std::string VideoSource::GetMimeType(const std::string& path) {
void VideoSource::StartDataRequestAfterPathExists( void VideoSource::StartDataRequestAfterPathExists(
const base::FilePath& video_path, const base::FilePath& video_path,
const content::URLDataSource::GotDataCallback& got_data_callback, content::URLDataSource::GotDataCallback got_data_callback,
bool path_exists) { bool path_exists) {
if (path_exists) { if (path_exists) {
auto video_data = std::make_unique<std::string>(); auto video_data = std::make_unique<std::string>();
@@ -105,10 +105,11 @@ void VideoSource::StartDataRequestAfterPathExists(
base::PostTaskAndReplyWithResult( base::PostTaskAndReplyWithResult(
task_runner_.get(), FROM_HERE, task_runner_.get(), FROM_HERE,
base::BindOnce(&base::ReadFileToString, video_path, data), base::BindOnce(&base::ReadFileToString, video_path, data),
base::BindOnce(&VideoLoaded, got_data_callback, std::move(video_data))); base::BindOnce(&VideoLoaded, std::move(got_data_callback),
std::move(video_data)));
} else { } else {
got_data_callback.Run(nullptr); std::move(got_data_callback).Run(nullptr);
} }
} }

@@ -29,17 +29,17 @@ class VideoSource : public content::URLDataSource {
// content::URLDataSource: // content::URLDataSource:
std::string GetSource() override; std::string GetSource() override;
void StartDataRequest(const GURL& url, void StartDataRequest(
const content::WebContents::Getter& wc_getter, const GURL& url,
const content::URLDataSource::GotDataCallback& const content::WebContents::Getter& wc_getter,
got_data_callback) override; content::URLDataSource::GotDataCallback got_data_callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
private: private:
// Continuation from StartDataRequest(). // Continuation from StartDataRequest().
void StartDataRequestAfterPathExists( void StartDataRequestAfterPathExists(
const base::FilePath& video_path, const base::FilePath& video_path,
const content::URLDataSource::GotDataCallback& got_data_callback, content::URLDataSource::GotDataCallback got_data_callback,
bool path_exists); bool path_exists);
// The background task runner on which file I/O is performed. // The background task runner on which file I/O is performed.

@@ -97,7 +97,7 @@ GURL GetCustomDevToolsFrontendURL() {
void DevToolsDataSource::StartDataRequest( void DevToolsDataSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const GotDataCallback& callback) { GotDataCallback callback) {
// Serve request to devtools://bundled/ from local bundle. // Serve request to devtools://bundled/ from local bundle.
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available. // TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
@@ -114,12 +114,12 @@ void DevToolsDataSource::StartDataRequest(
#if !BUILDFLAG(DEBUG_DEVTOOLS) #if !BUILDFLAG(DEBUG_DEVTOOLS)
if (!GetCustomDevToolsFrontendURL().SchemeIsFile()) { if (!GetCustomDevToolsFrontendURL().SchemeIsFile()) {
// Fetch from packaged resources. // Fetch from packaged resources.
StartBundledDataRequest(path_under_bundled, callback); StartBundledDataRequest(path_under_bundled, std::move(callback));
return; return;
} }
#endif #endif
// Fetch from file system. // Fetch from file system.
StartFileRequest(path_under_bundled, callback); StartFileRequest(path_under_bundled, std::move(callback));
return; return;
} }
@@ -127,7 +127,7 @@ void DevToolsDataSource::StartDataRequest(
std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath); std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath);
if (base::StartsWith(path, empty_path_prefix, if (base::StartsWith(path, empty_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) { base::CompareCase::INSENSITIVE_ASCII)) {
callback.Run(new base::RefCountedStaticMemory()); std::move(callback).Run(new base::RefCountedStaticMemory());
return; return;
} }
@@ -140,10 +140,10 @@ void DevToolsDataSource::StartDataRequest(
CHECK_EQ(url.host(), kRemoteFrontendDomain); CHECK_EQ(url.host(), kRemoteFrontendDomain);
if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) { if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) {
StartRemoteDataRequest(url, callback); StartRemoteDataRequest(url, std::move(callback));
} else { } else {
DLOG(ERROR) << "Refusing to load invalid remote front-end URL"; DLOG(ERROR) << "Refusing to load invalid remote front-end URL";
callback.Run(CreateNotFoundResponse()); std::move(callback).Run(CreateNotFoundResponse());
} }
return; return;
} }
@@ -158,12 +158,12 @@ void DevToolsDataSource::StartDataRequest(
GURL url = GURL(custom_devtools_frontend.spec() + GURL url = GURL(custom_devtools_frontend.spec() +
path.substr(custom_path_prefix.length())); path.substr(custom_path_prefix.length()));
DCHECK(url.is_valid()); DCHECK(url.is_valid());
StartCustomDataRequest(url, callback); StartCustomDataRequest(url, std::move(callback));
return; return;
} }
} }
callback.Run(CreateNotFoundResponse()); std::move(callback).Run(CreateNotFoundResponse());
} }
std::string DevToolsDataSource::GetMimeType(const std::string& path) { std::string DevToolsDataSource::GetMimeType(const std::string& path) {
@@ -184,7 +184,7 @@ bool DevToolsDataSource::ShouldServeMimeTypeAsContentTypeHeader() {
void DevToolsDataSource::StartBundledDataRequest( void DevToolsDataSource::StartBundledDataRequest(
const std::string& path, const std::string& path,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
scoped_refptr<base::RefCountedMemory> bytes = scoped_refptr<base::RefCountedMemory> bytes =
content::DevToolsFrontendHost::GetFrontendResourceBytes(path); content::DevToolsFrontendHost::GetFrontendResourceBytes(path);
@@ -192,12 +192,12 @@ void DevToolsDataSource::StartBundledDataRequest(
<< "Unable to find dev tool resource: " << path << "Unable to find dev tool resource: " << path
<< ". If you compiled with debug_devtools=1, try running with " << ". If you compiled with debug_devtools=1, try running with "
"--debug-devtools."; "--debug-devtools.";
callback.Run(bytes); std::move(callback).Run(bytes);
} }
void DevToolsDataSource::StartRemoteDataRequest( void DevToolsDataSource::StartRemoteDataRequest(
const GURL& url, const GURL& url,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
CHECK(url.is_valid()); CHECK(url.is_valid());
net::NetworkTrafficAnnotationTag traffic_annotation = net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("devtools_hard_coded_data_source", net::DefineNetworkTrafficAnnotation("devtools_hard_coded_data_source",
@@ -224,14 +224,15 @@ void DevToolsDataSource::StartRemoteDataRequest(
} }
})"); })");
StartNetworkRequest(url, traffic_annotation, net::LOAD_NORMAL, callback); StartNetworkRequest(url, traffic_annotation, net::LOAD_NORMAL,
std::move(callback));
} }
void DevToolsDataSource::StartCustomDataRequest( void DevToolsDataSource::StartCustomDataRequest(
const GURL& url, const GURL& url,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
if (!url.is_valid()) { if (!url.is_valid()) {
callback.Run(CreateNotFoundResponse()); std::move(callback).Run(CreateNotFoundResponse());
return; return;
} }
net::NetworkTrafficAnnotationTag traffic_annotation = net::NetworkTrafficAnnotationTag traffic_annotation =
@@ -264,20 +265,20 @@ void DevToolsDataSource::StartCustomDataRequest(
})"); })");
StartNetworkRequest(url, traffic_annotation, net::LOAD_DISABLE_CACHE, StartNetworkRequest(url, traffic_annotation, net::LOAD_DISABLE_CACHE,
callback); std::move(callback));
} }
void DevToolsDataSource::StartNetworkRequest( void DevToolsDataSource::StartNetworkRequest(
const GURL& url, const GURL& url,
const net::NetworkTrafficAnnotationTag& traffic_annotation, const net::NetworkTrafficAnnotationTag& traffic_annotation,
int load_flags, int load_flags,
const GotDataCallback& callback) { GotDataCallback callback) {
auto request = std::make_unique<network::ResourceRequest>(); auto request = std::make_unique<network::ResourceRequest>();
request->url = url; request->url = url;
request->load_flags = load_flags; request->load_flags = load_flags;
auto request_iter = pending_requests_.emplace(pending_requests_.begin()); auto request_iter = pending_requests_.emplace(pending_requests_.begin());
request_iter->callback = callback; request_iter->callback = std::move(callback);
request_iter->loader = request_iter->loader =
network::SimpleURLLoader::Create(std::move(request), traffic_annotation); network::SimpleURLLoader::Create(std::move(request), traffic_annotation);
request_iter->loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie( request_iter->loader->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
@@ -297,7 +298,7 @@ scoped_refptr<base::RefCountedMemory> ReadFileForDevTools(
} }
void DevToolsDataSource::StartFileRequest(const std::string& path, void DevToolsDataSource::StartFileRequest(const std::string& path,
const GotDataCallback& callback) { GotDataCallback callback) {
base::FilePath base_path; base::FilePath base_path;
GURL custom_devtools_frontend = GetCustomDevToolsFrontendURL(); GURL custom_devtools_frontend = GetCustomDevToolsFrontendURL();
if (custom_devtools_frontend.SchemeIsFile()) { if (custom_devtools_frontend.SchemeIsFile()) {
@@ -306,7 +307,7 @@ void DevToolsDataSource::StartFileRequest(const std::string& path,
#if BUILDFLAG(DEBUG_DEVTOOLS) #if BUILDFLAG(DEBUG_DEVTOOLS)
// Use default path for unbundled files when debug_devtools=true // Use default path for unbundled files when debug_devtools=true
if (!base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, &base_path)) { if (!base::PathService::Get(chrome::DIR_INSPECTOR_DEBUG, &base_path)) {
callback.Run(CreateNotFoundResponse()); std::move(callback).Run(CreateNotFoundResponse());
return; return;
} }
#else #else
@@ -322,10 +323,8 @@ void DevToolsDataSource::StartFileRequest(const std::string& path,
{base::MayBlock(), base::ThreadPool(), {base::MayBlock(), base::ThreadPool(),
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN,
base::TaskPriority::USER_VISIBLE}, base::TaskPriority::USER_VISIBLE},
// The usage of BindRepeating below is only because the type of base::BindOnce(ReadFileForDevTools, std::move(full_path)),
// task callback needs to match that of response callback, which std::move(callback));
// is currently a repeating callback.
base::BindRepeating(ReadFileForDevTools, std::move(full_path)), callback);
} }
void DevToolsDataSource::OnLoadComplete( void DevToolsDataSource::OnLoadComplete(
@@ -345,5 +344,5 @@ DevToolsDataSource::PendingRequest::PendingRequest(PendingRequest&& other) =
DevToolsDataSource::PendingRequest::~PendingRequest() { DevToolsDataSource::PendingRequest::~PendingRequest() {
if (callback) if (callback)
callback.Run(CreateNotFoundResponse()); std::move(callback).Run(CreateNotFoundResponse());
} }

@@ -41,7 +41,7 @@ class DevToolsDataSource : public content::URLDataSource {
void StartDataRequest(const GURL& url, void StartDataRequest(const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const GotDataCallback& callback) override; GotDataCallback callback) override;
private: private:
friend class DevToolsUIDataSourceTest; friend class DevToolsUIDataSourceTest;
@@ -59,23 +59,23 @@ class DevToolsDataSource : public content::URLDataSource {
// Serves bundled DevTools frontend from ResourceBundle. // Serves bundled DevTools frontend from ResourceBundle.
void StartBundledDataRequest(const std::string& path, void StartBundledDataRequest(const std::string& path,
const GotDataCallback& callback); GotDataCallback callback);
// Serves remote DevTools frontend from hard-coded App Engine domain. // Serves remote DevTools frontend from hard-coded App Engine domain.
void StartRemoteDataRequest(const GURL& url, const GotDataCallback& callback); void StartRemoteDataRequest(const GURL& url, GotDataCallback callback);
// Serves remote DevTools frontend from any endpoint, passed through // Serves remote DevTools frontend from any endpoint, passed through
// command-line flag. // command-line flag.
void StartCustomDataRequest(const GURL& url, const GotDataCallback& callback); void StartCustomDataRequest(const GURL& url, GotDataCallback callback);
virtual void StartNetworkRequest( virtual void StartNetworkRequest(
const GURL& url, const GURL& url,
const net::NetworkTrafficAnnotationTag& traffic_annotation, const net::NetworkTrafficAnnotationTag& traffic_annotation,
int load_flags, int load_flags,
const GotDataCallback& callback); GotDataCallback callback);
virtual void StartFileRequest(const std::string& path, virtual void StartFileRequest(const std::string& path,
const GotDataCallback& callback); GotDataCallback callback);
struct PendingRequest { struct PendingRequest {
PendingRequest(); PendingRequest();

@@ -49,15 +49,15 @@ class TestDevToolsDataSource : public DevToolsDataSource {
const GURL& url, const GURL& url,
const net::NetworkTrafficAnnotationTag& traffic_annotation, const net::NetworkTrafficAnnotationTag& traffic_annotation,
int load_flags, int load_flags,
const GotDataCallback& callback) override { GotDataCallback callback) override {
std::string result = "url: " + url.spec(); std::string result = "url: " + url.spec();
callback.Run(base::RefCountedString::TakeString(&result)); std::move(callback).Run(base::RefCountedString::TakeString(&result));
} }
void StartFileRequest(const std::string& path, void StartFileRequest(const std::string& path,
const GotDataCallback& callback) override { GotDataCallback callback) override {
std::string result = "file: " + path; std::string result = "file: " + path;
callback.Run(base::RefCountedString::TakeString(&result)); std::move(callback).Run(base::RefCountedString::TakeString(&result));
} }
}; };

@@ -115,17 +115,17 @@ std::string ExtensionIconSource::GetMimeType(const std::string&) {
void ExtensionIconSource::StartDataRequest( void ExtensionIconSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
// This is where everything gets started. First, parse the request and make // This is where everything gets started. First, parse the request and make
// the request data available for later. // the request data available for later.
static int next_id = 0; static int next_id = 0;
if (!ParseData(path, ++next_id, callback)) { if (!ParseData(path, ++next_id, &callback)) {
// If the request data cannot be parsed, request parameters will not be // If the request data cannot be parsed, request parameters will not be
// added to |request_map_|. // added to |request_map_|.
// Send back the default application icon (not resized or desaturated) as // Send back the default application icon (not resized or desaturated) as
// the default response. // the default response.
callback.Run(BitmapToMemory(GetDefaultAppImage()).get()); std::move(callback).Run(BitmapToMemory(GetDefaultAppImage()).get());
return; return;
} }
@@ -174,7 +174,7 @@ void ExtensionIconSource::FinalizeImage(const SkBitmap* image,
else else
bitmap = *image; bitmap = *image;
request->callback.Run(BitmapToMemory(&bitmap).get()); std::move(request->callback).Run(BitmapToMemory(&bitmap).get());
ClearData(request_id); ClearData(request_id);
} }
@@ -243,7 +243,7 @@ void ExtensionIconSource::OnFaviconDataAvailable(
if (!request->grayscale) { if (!request->grayscale) {
// If we don't need a grayscale image, then we can bypass FinalizeImage // If we don't need a grayscale image, then we can bypass FinalizeImage
// to avoid unnecessary conversions. // to avoid unnecessary conversions.
request->callback.Run(bitmap_result.bitmap_data.get()); std::move(request->callback).Run(bitmap_result.bitmap_data.get());
ClearData(request_id); ClearData(request_id);
} else { } else {
FinalizeImage(ToBitmap(bitmap_result.bitmap_data->front(), FinalizeImage(ToBitmap(bitmap_result.bitmap_data->front(),
@@ -273,7 +273,7 @@ void ExtensionIconSource::LoadIconFailed(int request_id) {
bool ExtensionIconSource::ParseData( bool ExtensionIconSource::ParseData(
const std::string& path, const std::string& path,
int request_id, int request_id,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback* callback) {
// Extract the parameters from the path by lower casing and splitting. // Extract the parameters from the path by lower casing and splitting.
std::string path_lower = base::ToLowerASCII(path); std::string path_lower = base::ToLowerASCII(path);
std::vector<std::string> path_parts = base::SplitString( std::vector<std::string> path_parts = base::SplitString(
@@ -309,21 +309,22 @@ bool ExtensionIconSource::ParseData(
bool grayscale = path_lower.find("grayscale=true") != std::string::npos; bool grayscale = path_lower.find("grayscale=true") != std::string::npos;
SetData(request_id, callback, extension, grayscale, size, match_type); SetData(request_id, std::move(*callback), extension, grayscale, size,
match_type);
return true; return true;
} }
void ExtensionIconSource::SetData( void ExtensionIconSource::SetData(
int request_id, int request_id,
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
const Extension* extension, const Extension* extension,
bool grayscale, bool grayscale,
int size, int size,
ExtensionIconSet::MatchType match) { ExtensionIconSet::MatchType match) {
std::unique_ptr<ExtensionIconRequest> request = std::unique_ptr<ExtensionIconRequest> request =
std::make_unique<ExtensionIconRequest>(); std::make_unique<ExtensionIconRequest>();
request->callback = callback; request->callback = std::move(callback);
request->extension = extension; request->extension = extension;
request->grayscale = grayscale; request->grayscale = grayscale;
request->size = size; request->size = size;

@@ -73,7 +73,7 @@ class ExtensionIconSource : public content::URLDataSource,
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
bool AllowCaching() override; bool AllowCaching() override;
private: private:
@@ -120,15 +120,15 @@ class ExtensionIconSource : public content::URLDataSource,
void LoadIconFailed(int request_id); void LoadIconFailed(int request_id);
// Parses and saves an ExtensionIconRequest for the URL |path| for the // Parses and saves an ExtensionIconRequest for the URL |path| for the
// specified |request_id|. // specified |request_id|. Takes the |callback| if it returns true.
bool ParseData(const std::string& path, bool ParseData(const std::string& path,
int request_id, int request_id,
const content::URLDataSource::GotDataCallback& callback); content::URLDataSource::GotDataCallback* callback);
// Stores the parameters associated with the |request_id|, making them // Stores the parameters associated with the |request_id|, making them
// as an ExtensionIconRequest via GetData. // as an ExtensionIconRequest via GetData.
void SetData(int request_id, void SetData(int request_id,
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
const Extension* extension, const Extension* extension,
bool grayscale, bool grayscale,
int size, int size,

@@ -436,9 +436,9 @@ std::string ExtensionsInternalsSource::GetMimeType(const std::string& path) {
void ExtensionsInternalsSource::StartDataRequest( void ExtensionsInternalsSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
std::string json = WriteToString(); std::string json = WriteToString();
callback.Run(base::RefCountedString::TakeString(&json)); std::move(callback).Run(base::RefCountedString::TakeString(&json));
} }
std::string ExtensionsInternalsSource::WriteToString() const { std::string ExtensionsInternalsSource::WriteToString() const {

@@ -23,7 +23,7 @@ class ExtensionsInternalsSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
// Simpler interface to generate string output, without needing to // Simpler interface to generate string output, without needing to
// call StartDataRequest. // call StartDataRequest.

@@ -77,27 +77,27 @@ std::string FaviconSource::GetSource() {
void FaviconSource::StartDataRequest( void FaviconSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
favicon::FaviconService* favicon_service = favicon::FaviconService* favicon_service =
FaviconServiceFactory::GetForProfile(profile_, FaviconServiceFactory::GetForProfile(profile_,
ServiceAccessType::EXPLICIT_ACCESS); ServiceAccessType::EXPLICIT_ACCESS);
if (!favicon_service) { if (!favicon_service) {
SendDefaultResponse(callback); SendDefaultResponse(std::move(callback));
return; return;
} }
chrome::ParsedFaviconPath parsed; chrome::ParsedFaviconPath parsed;
bool success = chrome::ParseFaviconPath(path, url_format_, &parsed); bool success = chrome::ParseFaviconPath(path, url_format_, &parsed);
if (!success) { if (!success) {
SendDefaultResponse(callback); SendDefaultResponse(std::move(callback));
return; return;
} }
GURL page_url(parsed.page_url); GURL page_url(parsed.page_url);
GURL icon_url(parsed.icon_url); GURL icon_url(parsed.icon_url);
if (!page_url.is_valid() && !icon_url.is_valid()) { if (!page_url.is_valid() && !icon_url.is_valid()) {
SendDefaultResponse(callback); SendDefaultResponse(std::move(callback));
return; return;
} }
@@ -111,9 +111,9 @@ void FaviconSource::StartDataRequest(
// IconType. // IconType.
favicon_service->GetRawFavicon( favicon_service->GetRawFavicon(
icon_url, favicon_base::IconType::kFavicon, desired_size_in_pixel, icon_url, favicon_base::IconType::kFavicon, desired_size_in_pixel,
base::BindRepeating(&FaviconSource::OnFaviconDataAvailable, base::BindOnce(&FaviconSource::OnFaviconDataAvailable,
base::Unretained(this), callback, base::Unretained(this), std::move(callback),
parsed.size_in_dip, parsed.device_scale_factor), parsed.size_in_dip, parsed.device_scale_factor),
&cancelable_task_tracker_); &cancelable_task_tracker_);
} else { } else {
// Intercept requests for prepopulated pages if TopSites exists. // Intercept requests for prepopulated pages if TopSites exists.
@@ -124,7 +124,7 @@ void FaviconSource::StartDataRequest(
if (page_url == prepopulated_page.most_visited.url) { if (page_url == prepopulated_page.most_visited.url) {
ui::ScaleFactor resource_scale_factor = ui::ScaleFactor resource_scale_factor =
ui::GetSupportedScaleFactor(parsed.device_scale_factor); ui::GetSupportedScaleFactor(parsed.device_scale_factor);
callback.Run( std::move(callback).Run(
ui::ResourceBundle::GetSharedInstance() ui::ResourceBundle::GetSharedInstance()
.LoadDataResourceBytesForScale(prepopulated_page.favicon_id, .LoadDataResourceBytesForScale(prepopulated_page.favicon_id,
resource_scale_factor)); resource_scale_factor));
@@ -144,9 +144,9 @@ void FaviconSource::StartDataRequest(
favicon_service->GetRawFaviconForPageURL( favicon_service->GetRawFaviconForPageURL(
page_url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel, page_url, {favicon_base::IconType::kFavicon}, desired_size_in_pixel,
fallback_to_host, fallback_to_host,
base::Bind(&FaviconSource::OnFaviconDataAvailable, base::BindOnce(&FaviconSource::OnFaviconDataAvailable,
base::Unretained(this), callback, parsed.size_in_dip, base::Unretained(this), std::move(callback),
parsed.device_scale_factor), parsed.size_in_dip, parsed.device_scale_factor),
&cancelable_task_tracker_); &cancelable_task_tracker_);
return; return;
} }
@@ -158,14 +158,14 @@ void FaviconSource::StartDataRequest(
HistoryUiFaviconRequestHandlerFactory::GetForBrowserContext( HistoryUiFaviconRequestHandlerFactory::GetForBrowserContext(
profile_); profile_);
if (!history_ui_favicon_request_handler) { if (!history_ui_favicon_request_handler) {
SendDefaultResponse(callback); SendDefaultResponse(std::move(callback));
return; return;
} }
history_ui_favicon_request_handler->GetRawFaviconForPageURL( history_ui_favicon_request_handler->GetRawFaviconForPageURL(
page_url, desired_size_in_pixel, page_url, desired_size_in_pixel,
base::BindOnce(&FaviconSource::OnFaviconDataAvailable, base::BindOnce(&FaviconSource::OnFaviconDataAvailable,
base::Unretained(this), callback, parsed.size_in_dip, base::Unretained(this), std::move(callback),
parsed.device_scale_factor), parsed.size_in_dip, parsed.device_scale_factor),
favicon::FaviconRequestPlatform::kDesktop, parsed_history_ui_origin, favicon::FaviconRequestPlatform::kDesktop, parsed_history_ui_origin,
/*icon_url_for_uma=*/ /*icon_url_for_uma=*/
GURL(parsed.icon_url), &cancelable_task_tracker_); GURL(parsed.icon_url), &cancelable_task_tracker_);
@@ -205,25 +205,25 @@ ui::NativeTheme* FaviconSource::GetNativeTheme() {
} }
void FaviconSource::OnFaviconDataAvailable( void FaviconSource::OnFaviconDataAvailable(
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
int size_in_dip, int size_in_dip,
float scale_factor, float scale_factor,
const favicon_base::FaviconRawBitmapResult& bitmap_result) { const favicon_base::FaviconRawBitmapResult& bitmap_result) {
if (bitmap_result.is_valid()) { if (bitmap_result.is_valid()) {
// Forward the data along to the networking system. // Forward the data along to the networking system.
callback.Run(bitmap_result.bitmap_data.get()); std::move(callback).Run(bitmap_result.bitmap_data.get());
} else { } else {
SendDefaultResponse(callback, size_in_dip, scale_factor); SendDefaultResponse(std::move(callback), size_in_dip, scale_factor);
} }
} }
void FaviconSource::SendDefaultResponse( void FaviconSource::SendDefaultResponse(
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
SendDefaultResponse(callback, 16, 1.0f); SendDefaultResponse(std::move(callback), 16, 1.0f);
} }
void FaviconSource::SendDefaultResponse( void FaviconSource::SendDefaultResponse(
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
int size_in_dip, int size_in_dip,
float scale_factor) { float scale_factor) {
const bool dark = GetNativeTheme()->ShouldUseDarkColors(); const bool dark = GetNativeTheme()->ShouldUseDarkColors();
@@ -239,7 +239,7 @@ void FaviconSource::SendDefaultResponse(
resource_id = dark ? IDR_DEFAULT_FAVICON_DARK : IDR_DEFAULT_FAVICON; resource_id = dark ? IDR_DEFAULT_FAVICON_DARK : IDR_DEFAULT_FAVICON;
break; break;
} }
callback.Run(LoadIconBytes(scale_factor, resource_id)); std::move(callback).Run(LoadIconBytes(scale_factor, resource_id));
} }
base::RefCountedMemory* FaviconSource::LoadIconBytes(float scale_factor, base::RefCountedMemory* FaviconSource::LoadIconBytes(float scale_factor,

@@ -46,7 +46,7 @@ class FaviconSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string&) override; std::string GetMimeType(const std::string&) override;
bool AllowCaching() override; bool AllowCaching() override;
bool ShouldReplaceExistingSource() override; bool ShouldReplaceExistingSource() override;
@@ -75,20 +75,18 @@ class FaviconSource : public content::URLDataSource {
// |bitmap_result| is valid, returns it to caller using |callback|. Otherwise // |bitmap_result| is valid, returns it to caller using |callback|. Otherwise
// will send appropriate default icon for |size_in_dip| and |scale_factor|. // will send appropriate default icon for |size_in_dip| and |scale_factor|.
void OnFaviconDataAvailable( void OnFaviconDataAvailable(
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
int size_in_dip, int size_in_dip,
float scale_factor, float scale_factor,
const favicon_base::FaviconRawBitmapResult& bitmap_result); const favicon_base::FaviconRawBitmapResult& bitmap_result);
// Sends the 16x16 DIP 1x default favicon. // Sends the 16x16 DIP 1x default favicon.
void SendDefaultResponse( void SendDefaultResponse(content::URLDataSource::GotDataCallback callback);
const content::URLDataSource::GotDataCallback& callback);
// Sends the default favicon. // Sends the default favicon.
void SendDefaultResponse( void SendDefaultResponse(content::URLDataSource::GotDataCallback callback,
const content::URLDataSource::GotDataCallback& callback, int size_in_dip,
int size_in_dip, float scale_factor);
float scale_factor);
chrome::FaviconUrlFormat url_format_; chrome::FaviconUrlFormat url_format_;

@@ -65,24 +65,21 @@ void ParseQueryParams(const std::string& path,
} // namespace } // namespace
FileIconSource::IconRequestDetails::IconRequestDetails() : scale_factor(1.0f) { FileIconSource::IconRequestDetails::IconRequestDetails() = default;
}
FileIconSource::IconRequestDetails::IconRequestDetails( FileIconSource::IconRequestDetails::IconRequestDetails(
const IconRequestDetails& other) = default; IconRequestDetails&& other) = default;
FileIconSource::IconRequestDetails& FileIconSource::IconRequestDetails::
operator=(IconRequestDetails&& other) = default;
FileIconSource::IconRequestDetails::~IconRequestDetails() = default;
FileIconSource::IconRequestDetails::~IconRequestDetails() { FileIconSource::FileIconSource() = default;
} FileIconSource::~FileIconSource() = default;
FileIconSource::FileIconSource() {}
FileIconSource::~FileIconSource() {}
void FileIconSource::FetchFileIcon( void FileIconSource::FetchFileIcon(
const base::FilePath& path, const base::FilePath& path,
float scale_factor, float scale_factor,
IconLoader::IconSize icon_size, IconLoader::IconSize icon_size,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
IconManager* im = g_browser_process->icon_manager(); IconManager* im = g_browser_process->icon_manager();
gfx::Image* icon = im->LookupIconFromFilepath(path, icon_size); gfx::Image* icon = im->LookupIconFromFilepath(path, icon_size);
@@ -92,18 +89,17 @@ void FileIconSource::FetchFileIcon(
icon->ToImageSkia()->GetRepresentation(scale_factor).GetBitmap(), false, icon->ToImageSkia()->GetRepresentation(scale_factor).GetBitmap(), false,
&icon_data->data()); &icon_data->data());
callback.Run(icon_data.get()); std::move(callback).Run(icon_data.get());
} else { } else {
// Attach the ChromeURLDataManager request ID to the history request. // Attach the ChromeURLDataManager request ID to the history request.
IconRequestDetails details; IconRequestDetails details;
details.callback = callback; details.callback = std::move(callback);
details.scale_factor = scale_factor; details.scale_factor = scale_factor;
// Icon was not in cache, go fetch it slowly. // Icon was not in cache, go fetch it slowly.
im->LoadIcon(path, im->LoadIcon(path, icon_size,
icon_size, base::BindOnce(&FileIconSource::OnFileIconDataAvailable,
base::Bind(&FileIconSource::OnFileIconDataAvailable, base::Unretained(this), std::move(details)),
base::Unretained(this), details),
&cancelable_task_tracker_); &cancelable_task_tracker_);
} }
} }
@@ -115,14 +111,14 @@ std::string FileIconSource::GetSource() {
void FileIconSource::StartDataRequest( void FileIconSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
base::FilePath file_path; base::FilePath file_path;
IconLoader::IconSize icon_size = IconLoader::NORMAL; IconLoader::IconSize icon_size = IconLoader::NORMAL;
float scale_factor = 1.0f; float scale_factor = 1.0f;
// TODO(crbug/1009127): Make ParseQueryParams take GURL. // TODO(crbug/1009127): Make ParseQueryParams take GURL.
ParseQueryParams(path, &file_path, &scale_factor, &icon_size); ParseQueryParams(path, &file_path, &scale_factor, &icon_size);
FetchFileIcon(file_path, scale_factor, icon_size, callback); FetchFileIcon(file_path, scale_factor, icon_size, std::move(callback));
} }
std::string FileIconSource::GetMimeType(const std::string&) { std::string FileIconSource::GetMimeType(const std::string&) {
@@ -134,7 +130,7 @@ bool FileIconSource::AllowCaching() {
return false; return false;
} }
void FileIconSource::OnFileIconDataAvailable(const IconRequestDetails& details, void FileIconSource::OnFileIconDataAvailable(IconRequestDetails details,
gfx::Image icon) { gfx::Image icon) {
if (!icon.IsEmpty()) { if (!icon.IsEmpty()) {
scoped_refptr<base::RefCountedBytes> icon_data(new base::RefCountedBytes); scoped_refptr<base::RefCountedBytes> icon_data(new base::RefCountedBytes);
@@ -142,9 +138,9 @@ void FileIconSource::OnFileIconDataAvailable(const IconRequestDetails& details,
icon.ToImageSkia()->GetRepresentation(details.scale_factor).GetBitmap(), icon.ToImageSkia()->GetRepresentation(details.scale_factor).GetBitmap(),
false, &icon_data->data()); false, &icon_data->data());
details.callback.Run(icon_data.get()); std::move(details.callback).Run(icon_data.get());
} else { } else {
// TODO(glen): send a dummy icon. // TODO(glen): send a dummy icon.
details.callback.Run(nullptr); std::move(details.callback).Run(nullptr);
} }
} }

@@ -29,7 +29,7 @@ class FileIconSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string&) override; std::string GetMimeType(const std::string&) override;
bool AllowCaching() override; bool AllowCaching() override;
@@ -37,29 +37,30 @@ class FileIconSource : public content::URLDataSource {
// Once the |path| and |icon_size| has been determined from the request, this // Once the |path| and |icon_size| has been determined from the request, this
// function is called to perform the actual fetch. Declared as virtual for // function is called to perform the actual fetch. Declared as virtual for
// testing. // testing.
virtual void FetchFileIcon( virtual void FetchFileIcon(const base::FilePath& path,
const base::FilePath& path, float scale_factor,
float scale_factor, IconLoader::IconSize icon_size,
IconLoader::IconSize icon_size, content::URLDataSource::GotDataCallback callback);
const content::URLDataSource::GotDataCallback& callback);
private: private:
// Contains the necessary information for completing an icon fetch request. // Contains the necessary information for completing an icon fetch request.
struct IconRequestDetails { struct IconRequestDetails {
IconRequestDetails(); IconRequestDetails();
IconRequestDetails(const IconRequestDetails& other);
IconRequestDetails(IconRequestDetails&& other);
IconRequestDetails& operator=(IconRequestDetails&& other);
~IconRequestDetails(); ~IconRequestDetails();
// The callback to run with the response. // The callback to run with the response.
content::URLDataSource::GotDataCallback callback; content::URLDataSource::GotDataCallback callback;
// The requested scale factor to respond with. // The requested scale factor to respond with.
float scale_factor; float scale_factor = 1;
}; };
// Called when favicon data is available from the history backend. // Called when favicon data is available from the history backend.
void OnFileIconDataAvailable(const IconRequestDetails& details, void OnFileIconDataAvailable(IconRequestDetails details, gfx::Image icon);
gfx::Image icon);
// Tracks tasks requesting file icons. // Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_; base::CancelableTaskTracker cancelable_task_tracker_;

@@ -22,11 +22,18 @@ class TestFileIconSource : public FileIconSource {
public: public:
TestFileIconSource() {} TestFileIconSource() {}
MOCK_METHOD4(FetchFileIcon, void FetchFileIcon(
const base::FilePath& path,
float scale_factor,
IconLoader::IconSize icon_size,
content::URLDataSource::GotDataCallback callback) override {
FetchFileIcon_(path, scale_factor, icon_size, callback);
}
MOCK_METHOD4(FetchFileIcon_,
void(const base::FilePath& path, void(const base::FilePath& path,
float scale_factor, float scale_factor,
IconLoader::IconSize icon_size, IconLoader::IconSize icon_size,
const content::URLDataSource::GotDataCallback& callback)); content::URLDataSource::GotDataCallback& callback));
~TestFileIconSource() override {} ~TestFileIconSource() override {}
}; };
@@ -115,14 +122,14 @@ TEST_F(FileIconSourceTest, FileIconSource_Parse) {
for (unsigned i = 0; i < base::size(kBasicExpectations); i++) { for (unsigned i = 0; i < base::size(kBasicExpectations); i++) {
auto source = std::make_unique<TestFileIconSource>(); auto source = std::make_unique<TestFileIconSource>();
content::URLDataSource::GotDataCallback callback; content::URLDataSource::GotDataCallback callback;
EXPECT_CALL(*source.get(), EXPECT_CALL(
FetchFileIcon( *source.get(),
base::FilePath(kBasicExpectations[i].unescaped_path), FetchFileIcon_(base::FilePath(kBasicExpectations[i].unescaped_path),
kBasicExpectations[i].scale_factor, kBasicExpectations[i].scale_factor,
kBasicExpectations[i].size, CallbackIsNull())); kBasicExpectations[i].size, CallbackIsNull()));
source->StartDataRequest( source->StartDataRequest(
GURL(base::StrCat( GURL(base::StrCat(
{"chrome://any-host/", kBasicExpectations[i].request_path})), {"chrome://any-host/", kBasicExpectations[i].request_path})),
content::WebContents::Getter(), callback); content::WebContents::Getter(), std::move(callback));
} }
} }

@@ -97,7 +97,7 @@ class InterstitialHTMLSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
private: private:
#if BUILDFLAG(ENABLE_SUPERVISED_USERS) #if BUILDFLAG(ENABLE_SUPERVISED_USERS)
@@ -479,7 +479,7 @@ std::string InterstitialHTMLSource::GetContentSecurityPolicyImgSrc() {
void InterstitialHTMLSource::StartDataRequest( void InterstitialHTMLSource::StartDataRequest(
const GURL& request_url, const GURL& request_url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
// TODO(crbug/1009127): Simplify usages of |path| since |request_url| is // TODO(crbug/1009127): Simplify usages of |path| since |request_url| is
// available. // available.
const std::string path = const std::string path =
@@ -536,7 +536,7 @@ void InterstitialHTMLSource::StartDataRequest(
} }
scoped_refptr<base::RefCountedString> html_bytes = new base::RefCountedString; scoped_refptr<base::RefCountedString> html_bytes = new base::RefCountedString;
html_bytes->data().assign(html.begin(), html.end()); html_bytes->data().assign(html.begin(), html.end());
callback.Run(html_bytes.get()); std::move(callback).Run(html_bytes.get());
} }
#if BUILDFLAG(ENABLE_SUPERVISED_USERS) #if BUILDFLAG(ENABLE_SUPERVISED_USERS)

@@ -154,7 +154,7 @@ std::string NewTabUI::NewTabHTMLSource::GetSource() {
void NewTabUI::NewTabHTMLSource::StartDataRequest( void NewTabUI::NewTabHTMLSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available. // TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
@@ -162,7 +162,7 @@ void NewTabUI::NewTabHTMLSource::StartDataRequest(
// A path under new-tab was requested; it's likely a bad relative // A path under new-tab was requested; it's likely a bad relative
// URL from the new tab page, but in any case it's an error. // URL from the new tab page, but in any case it's an error.
NOTREACHED() << path << " should not have been requested on the NTP"; NOTREACHED() << path << " should not have been requested on the NTP";
callback.Run(nullptr); std::move(callback).Run(nullptr);
return; return;
} }
@@ -175,7 +175,7 @@ void NewTabUI::NewTabHTMLSource::StartDataRequest(
NTPResourceCacheFactory::GetForProfile(profile_)-> NTPResourceCacheFactory::GetForProfile(profile_)->
GetNewTabHTML(win_type)); GetNewTabHTML(win_type));
callback.Run(html_bytes.get()); std::move(callback).Run(html_bytes.get());
} }
std::string NewTabUI::NewTabHTMLSource::GetMimeType( std::string NewTabUI::NewTabHTMLSource::GetMimeType(

@@ -58,7 +58,7 @@ class NewTabUI : public content::WebUIController {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string&) override; std::string GetMimeType(const std::string&) override;
bool ShouldReplaceExistingSource() override; bool ShouldReplaceExistingSource() override;
std::string GetContentSecurityPolicyScriptSrc() override; std::string GetContentSecurityPolicyScriptSrc() override;

@@ -30,7 +30,7 @@ std::string PrefsInternalsSource::GetMimeType(const std::string& path) {
void PrefsInternalsSource::StartDataRequest( void PrefsInternalsSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::string json; std::string json;
std::unique_ptr<base::DictionaryValue> prefs = std::unique_ptr<base::DictionaryValue> prefs =
@@ -38,5 +38,5 @@ void PrefsInternalsSource::StartDataRequest(
DCHECK(prefs); DCHECK(prefs);
CHECK(base::JSONWriter::WriteWithOptions( CHECK(base::JSONWriter::WriteWithOptions(
*prefs, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json)); *prefs, base::JSONWriter::OPTIONS_PRETTY_PRINT, &json));
callback.Run(base::RefCountedString::TakeString(&json)); std::move(callback).Run(base::RefCountedString::TakeString(&json));
} }

@@ -22,7 +22,7 @@ class PrefsInternalsSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
private: private:
Profile* profile_; Profile* profile_;

@@ -146,9 +146,8 @@ bool ShouldHandleRequestCallback(const std::string& path) {
} }
// Get markup or other resources for the print preview page. // Get markup or other resources for the print preview page.
void HandleRequestCallback( void HandleRequestCallback(const std::string& path,
const std::string& path, content::WebUIDataSource::GotDataCallback callback) {
const content::WebUIDataSource::GotDataCallback& callback) {
// ChromeWebUIDataSource handles most requests except for the print preview // ChromeWebUIDataSource handles most requests except for the print preview
// data. // data.
int preview_ui_id; int preview_ui_id;
@@ -159,12 +158,12 @@ void HandleRequestCallback(
PrintPreviewDataService::GetInstance()->GetDataEntry(preview_ui_id, PrintPreviewDataService::GetInstance()->GetDataEntry(preview_ui_id,
page_index, &data); page_index, &data);
if (data.get()) { if (data.get()) {
callback.Run(data.get()); std::move(callback).Run(data.get());
return; return;
} }
// Invalid request. // Invalid request.
auto empty_bytes = base::MakeRefCounted<base::RefCountedBytes>(); auto empty_bytes = base::MakeRefCounted<base::RefCountedBytes>();
callback.Run(empty_bytes.get()); std::move(callback).Run(empty_bytes.get());
} }
void AddPrintPreviewStrings(content::WebUIDataSource* source) { void AddPrintPreviewStrings(content::WebUIDataSource* source) {

@@ -45,13 +45,13 @@ std::string TestDataSource::GetSource() {
void TestDataSource::StartDataRequest( void TestDataSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
base::PostTask( base::PostTask(
FROM_HERE, FROM_HERE,
{base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING},
base::BindOnce(&TestDataSource::ReadFile, base::Unretained(this), path, base::BindOnce(&TestDataSource::ReadFile, base::Unretained(this), path,
callback)); std::move(callback)));
} }
std::string TestDataSource::GetMimeType(const std::string& path) { std::string TestDataSource::GetMimeType(const std::string& path) {
@@ -87,7 +87,7 @@ GURL TestDataSource::GetURLForPath(const std::string& path) {
void TestDataSource::ReadFile( void TestDataSource::ReadFile(
const std::string& path, const std::string& path,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
std::string content; std::string content;
GURL url = GetURLForPath(path); GURL url = GetURLForPath(path);
@@ -125,5 +125,5 @@ void TestDataSource::ReadFile(
scoped_refptr<base::RefCountedString> response = scoped_refptr<base::RefCountedString> response =
base::RefCountedString::TakeString(&content); base::RefCountedString::TakeString(&content);
callback.Run(response.get()); std::move(callback).Run(response.get());
} }

@@ -22,7 +22,7 @@ class TestDataSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
@@ -37,7 +37,7 @@ class TestDataSource : public content::URLDataSource {
GURL GetURLForPath(const std::string& path); GURL GetURLForPath(const std::string& path);
void ReadFile(const std::string& path, void ReadFile(const std::string& path,
const content::URLDataSource::GotDataCallback& callback); content::URLDataSource::GotDataCallback callback);
base::FilePath src_root_; base::FilePath src_root_;
base::FilePath gen_root_; base::FilePath gen_root_;

@@ -29,7 +29,7 @@ bool ShouldHandleTestFileRequestCallback(const std::string& path) {
void HandleTestFileRequestCallback( void HandleTestFileRequestCallback(
const std::string& path, const std::string& path,
const content::WebUIDataSource::GotDataCallback& callback) { content::WebUIDataSource::GotDataCallback callback) {
DCHECK(ShouldHandleTestFileRequestCallback(path)); DCHECK(ShouldHandleTestFileRequestCallback(path));
base::ScopedAllowBlockingForTesting allow_blocking; base::ScopedAllowBlockingForTesting allow_blocking;
@@ -44,7 +44,7 @@ void HandleTestFileRequestCallback(
base::RefCountedString* ref_contents = new base::RefCountedString(); base::RefCountedString* ref_contents = new base::RefCountedString();
ref_contents->data() = contents; ref_contents->data() = contents;
callback.Run(ref_contents); std::move(callback).Run(ref_contents);
} }
} // namespace } // namespace

@@ -84,7 +84,7 @@ std::string ThemeSource::GetSource() {
void ThemeSource::StartDataRequest( void ThemeSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available. // TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
const std::string path = content::URLDataSource::URLToRequestPath(url); const std::string path = content::URLDataSource::URLToRequestPath(url);
// Default scale factor if not specified. // Default scale factor if not specified.
@@ -99,7 +99,7 @@ void ThemeSource::StartDataRequest(
NTPResourceCache::WindowType type = NTPResourceCache::WindowType type =
NTPResourceCache::GetWindowType(profile_, /*render_host=*/nullptr); NTPResourceCache::GetWindowType(profile_, /*render_host=*/nullptr);
NTPResourceCache* cache = NTPResourceCacheFactory::GetForProfile(profile_); NTPResourceCache* cache = NTPResourceCacheFactory::GetForProfile(profile_);
callback.Run(cache->GetNewTabCSS(type)); std::move(callback).Run(cache->GetNewTabCSS(type));
return; return;
} }
@@ -150,16 +150,16 @@ void ThemeSource::StartDataRequest(
// URLs are only used by WebUI pages and component extensions. However, the // URLs are only used by WebUI pages and component extensions. However, the
// user can also enter these into the omnibox, so we need to fail // user can also enter these into the omnibox, so we need to fail
// gracefully. // gracefully.
callback.Run(nullptr); std::move(callback).Run(nullptr);
} else if ((GetMimeType(path) == "image/png") && } else if ((GetMimeType(path) == "image/png") &&
((scale > max_scale) || (frame != -1))) { ((scale > max_scale) || (frame != -1))) {
// This will extract and scale frame 0 of animated images. // This will extract and scale frame 0 of animated images.
// TODO(reveman): Support scaling of animated images and avoid scaling and // TODO(reveman): Support scaling of animated images and avoid scaling and
// re-encode when specific frame is specified (crbug.com/750064). // re-encode when specific frame is specified (crbug.com/750064).
DCHECK_LE(frame, 0); DCHECK_LE(frame, 0);
SendThemeImage(callback, resource_id, scale); SendThemeImage(std::move(callback), resource_id, scale);
} else { } else {
SendThemeBitmap(callback, resource_id, scale); SendThemeBitmap(std::move(callback), resource_id, scale);
} }
} }
@@ -206,7 +206,7 @@ bool ThemeSource::ShouldServiceRequest(
// ThemeSource, private: // ThemeSource, private:
void ThemeSource::SendThemeBitmap( void ThemeSource::SendThemeBitmap(
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
int resource_id, int resource_id,
float scale) { float scale) {
ui::ScaleFactor scale_factor = ui::GetSupportedScaleFactor(scale); ui::ScaleFactor scale_factor = ui::GetSupportedScaleFactor(scale);
@@ -215,16 +215,17 @@ void ThemeSource::SendThemeBitmap(
scoped_refptr<base::RefCountedMemory> image_data( scoped_refptr<base::RefCountedMemory> image_data(
ThemeService::GetThemeProviderForProfile(profile_->GetOriginalProfile()) ThemeService::GetThemeProviderForProfile(profile_->GetOriginalProfile())
.GetRawData(resource_id, scale_factor)); .GetRawData(resource_id, scale_factor));
callback.Run(image_data.get()); std::move(callback).Run(image_data.get());
} else { } else {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
const ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); const ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
callback.Run(rb.LoadDataResourceBytesForScale(resource_id, scale_factor)); std::move(callback).Run(
rb.LoadDataResourceBytesForScale(resource_id, scale_factor));
} }
} }
void ThemeSource::SendThemeImage( void ThemeSource::SendThemeImage(
const content::URLDataSource::GotDataCallback& callback, content::URLDataSource::GotDataCallback callback,
int resource_id, int resource_id,
float scale) { float scale) {
scoped_refptr<base::RefCountedBytes> data(new base::RefCountedBytes()); scoped_refptr<base::RefCountedBytes> data(new base::RefCountedBytes());
@@ -233,7 +234,7 @@ void ThemeSource::SendThemeImage(
const ui::ThemeProvider& tp = ThemeService::GetThemeProviderForProfile( const ui::ThemeProvider& tp = ThemeService::GetThemeProviderForProfile(
profile_->GetOriginalProfile()); profile_->GetOriginalProfile());
ProcessImageOnUiThread(*tp.GetImageSkiaNamed(resource_id), scale, data); ProcessImageOnUiThread(*tp.GetImageSkiaNamed(resource_id), scale, data);
callback.Run(data.get()); std::move(callback).Run(data.get());
} else { } else {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
// Fetching image data in ResourceBundle should happen on the UI thread. See // Fetching image data in ResourceBundle should happen on the UI thread. See
@@ -241,7 +242,7 @@ void ThemeSource::SendThemeImage(
base::PostTaskAndReply( base::PostTaskAndReply(
FROM_HERE, {content::BrowserThread::UI}, FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&ProcessResourceOnUiThread, resource_id, scale, data), base::BindOnce(&ProcessResourceOnUiThread, resource_id, scale, data),
base::BindOnce(callback, data)); base::BindOnce(std::move(callback), data));
} }
} }

@@ -25,7 +25,7 @@ class ThemeSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
scoped_refptr<base::SingleThreadTaskRunner> TaskRunnerForRequestPath( scoped_refptr<base::SingleThreadTaskRunner> TaskRunnerForRequestPath(
const std::string& path) override; const std::string& path) override;
@@ -38,14 +38,14 @@ class ThemeSource : public content::URLDataSource {
private: private:
// Fetches and sends the theme bitmap. // Fetches and sends the theme bitmap.
void SendThemeBitmap(const content::URLDataSource::GotDataCallback& callback, void SendThemeBitmap(content::URLDataSource::GotDataCallback callback,
int resource_id, int resource_id,
float scale); float scale);
// Used in place of SendThemeBitmap when the desired scale is larger than // Used in place of SendThemeBitmap when the desired scale is larger than
// what the resource bundle supports. This can rescale the provided bitmap up // what the resource bundle supports. This can rescale the provided bitmap up
// to the desired size. // to the desired size.
void SendThemeImage(const content::URLDataSource::GotDataCallback& callback, void SendThemeImage(content::URLDataSource::GotDataCallback callback,
int resource_id, int resource_id,
float scale); float scale);

@@ -28,7 +28,9 @@ class WebUISourcesTest : public testing::Test {
theme_source()->StartDataRequest( theme_source()->StartDataRequest(
GURL(base::StrCat({content::kChromeUIScheme, "://", GURL(base::StrCat({content::kChromeUIScheme, "://",
chrome::kChromeUIThemeHost, "/", source})), chrome::kChromeUIThemeHost, "/", source})),
content::WebContents::Getter(), callback_); content::WebContents::Getter(),
base::BindOnce(&WebUISourcesTest::SendResponse,
base::Unretained(this)));
} }
size_t result_data_size_; size_t result_data_size_;
@@ -37,8 +39,6 @@ class WebUISourcesTest : public testing::Test {
void SetUp() override { void SetUp() override {
profile_ = std::make_unique<TestingProfile>(); profile_ = std::make_unique<TestingProfile>();
theme_source_ = std::make_unique<ThemeSource>(profile_.get()); theme_source_ = std::make_unique<ThemeSource>(profile_.get());
callback_ = base::Bind(&WebUISourcesTest::SendResponse,
base::Unretained(this));
} }
void TearDown() override { void TearDown() override {
@@ -50,8 +50,6 @@ class WebUISourcesTest : public testing::Test {
result_data_size_ = data ? data->size() : 0; result_data_size_ = data ? data->size() : 0;
} }
content::URLDataSource::GotDataCallback callback_;
content::BrowserTaskEnvironment task_environment_; content::BrowserTaskEnvironment task_environment_;
std::unique_ptr<TestingProfile> profile_; std::unique_ptr<TestingProfile> profile_;

@@ -21,9 +21,9 @@ namespace welcome {
NtpBackgroundFetcher::NtpBackgroundFetcher( NtpBackgroundFetcher::NtpBackgroundFetcher(
size_t index, size_t index,
const content::WebUIDataSource::GotDataCallback& callback) content::WebUIDataSource::GotDataCallback callback)
: index_(index), callback_(callback) { : index_(index), callback_(std::move(callback)) {
DCHECK(callback_ && !callback_.is_null()); DCHECK(callback_);
net::NetworkTrafficAnnotationTag traffic_annotation = net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("nux_ntp_background_preview", R"( net::DefineNetworkTrafficAnnotation("nux_ntp_background_preview", R"(
semantics { semantics {
@@ -74,9 +74,10 @@ NtpBackgroundFetcher::~NtpBackgroundFetcher() = default;
void NtpBackgroundFetcher::OnFetchCompleted( void NtpBackgroundFetcher::OnFetchCompleted(
std::unique_ptr<std::string> response_body) { std::unique_ptr<std::string> response_body) {
if (response_body) { if (response_body) {
callback_.Run(base::RefCountedString::TakeString(response_body.release())); std::move(callback_).Run(
base::RefCountedString::TakeString(response_body.release()));
} else { } else {
callback_.Run(base::MakeRefCounted<base::RefCountedBytes>()); std::move(callback_).Run(base::MakeRefCounted<base::RefCountedBytes>());
} }
} }

@@ -20,9 +20,8 @@ namespace welcome {
class NtpBackgroundFetcher { class NtpBackgroundFetcher {
public: public:
NtpBackgroundFetcher( NtpBackgroundFetcher(size_t index,
size_t index, content::WebUIDataSource::GotDataCallback callback);
const content::WebUIDataSource::GotDataCallback& callback);
~NtpBackgroundFetcher(); ~NtpBackgroundFetcher();
private: private:

@@ -54,10 +54,9 @@ bool ShouldHandleRequestCallback(base::WeakPtr<WelcomeUI> weak_ptr,
return !!weak_ptr; return !!weak_ptr;
} }
void HandleRequestCallback( void HandleRequestCallback(base::WeakPtr<WelcomeUI> weak_ptr,
base::WeakPtr<WelcomeUI> weak_ptr, const std::string& path,
const std::string& path, content::WebUIDataSource::GotDataCallback callback) {
const content::WebUIDataSource::GotDataCallback& callback) {
DCHECK(ShouldHandleRequestCallback(weak_ptr, path)); DCHECK(ShouldHandleRequestCallback(weak_ptr, path));
std::string index_param = path.substr(path.find_first_of("?") + 1); std::string index_param = path.substr(path.find_first_of("?") + 1);
@@ -66,7 +65,7 @@ void HandleRequestCallback(
background_index < 0); background_index < 0);
DCHECK(weak_ptr); DCHECK(weak_ptr);
weak_ptr->CreateBackgroundFetcher(background_index, callback); weak_ptr->CreateBackgroundFetcher(background_index, std::move(callback));
} }
void AddStrings(content::WebUIDataSource* html_source) { void AddStrings(content::WebUIDataSource* html_source) {
@@ -204,9 +203,9 @@ WelcomeUI::~WelcomeUI() {}
void WelcomeUI::CreateBackgroundFetcher( void WelcomeUI::CreateBackgroundFetcher(
size_t background_index, size_t background_index,
const content::WebUIDataSource::GotDataCallback& callback) { content::WebUIDataSource::GotDataCallback callback) {
background_fetcher_ = std::make_unique<welcome::NtpBackgroundFetcher>( background_fetcher_ = std::make_unique<welcome::NtpBackgroundFetcher>(
background_index, callback); background_index, std::move(callback));
} }
void WelcomeUI::StorePageSeen(Profile* profile) { void WelcomeUI::StorePageSeen(Profile* profile) {

@@ -26,7 +26,7 @@ class WelcomeUI : public content::WebUIController {
void CreateBackgroundFetcher( void CreateBackgroundFetcher(
size_t background_index, size_t background_index,
const content::WebUIDataSource::GotDataCallback& callback); content::WebUIDataSource::GotDataCallback callback);
protected: protected:
// Visible for testing. // Visible for testing.

@@ -82,7 +82,7 @@ class TestWebUIController : public content::WebUIController {
}), }),
base::BindRepeating( base::BindRepeating(
[](const std::string& id, [](const std::string& id,
const content::WebUIDataSource::GotDataCallback& callback) { content::WebUIDataSource::GotDataCallback callback) {
scoped_refptr<base::RefCountedString> ref_contents( scoped_refptr<base::RefCountedString> ref_contents(
new base::RefCountedString); new base::RefCountedString);
if (id == "manifest.json") if (id == "manifest.json")
@@ -92,7 +92,7 @@ class TestWebUIController : public content::WebUIController {
else else
NOTREACHED(); NOTREACHED();
callback.Run(ref_contents); std::move(callback).Run(ref_contents);
})); }));
content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(), content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(),
data_source); data_source);

@@ -347,9 +347,6 @@ void BaseWebUIBrowserTest::BrowsePrintPreload(const GURL& browse_to) {
#endif #endif
} }
const std::string BaseWebUIBrowserTest::kDummyURL =
content::GetWebUIURLString("DummyURL");
BaseWebUIBrowserTest::BaseWebUIBrowserTest() BaseWebUIBrowserTest::BaseWebUIBrowserTest()
: libraries_preloaded_(false), override_selected_web_ui_(nullptr) {} : libraries_preloaded_(false), override_selected_web_ui_(nullptr) {}
@@ -369,6 +366,11 @@ void BaseWebUIBrowserTest::set_webui_host(const std::string& webui_host) {
namespace { namespace {
const GURL& DummyUrl() {
static GURL url(content::GetWebUIURLString("DummyURL"));
return url;
}
// DataSource for the dummy URL. If no data source is provided then an error // DataSource for the dummy URL. If no data source is provided then an error
// page is shown. While this doesn't matter for most tests, without it, // page is shown. While this doesn't matter for most tests, without it,
// navigation to different anchors cannot be listened to (via the hashchange // navigation to different anchors cannot be listened to (via the hashchange
@@ -384,11 +386,11 @@ class MockWebUIDataSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override { content::URLDataSource::GotDataCallback callback) override {
std::string dummy_html = "<html><body>Dummy</body></html>"; std::string dummy_html = "<html><body>Dummy</body></html>";
scoped_refptr<base::RefCountedString> response = scoped_refptr<base::RefCountedString> response =
base::RefCountedString::TakeString(&dummy_html); base::RefCountedString::TakeString(&dummy_html);
callback.Run(response.get()); std::move(callback).Run(response.get());
} }
std::string GetMimeType(const std::string& path) override { std::string GetMimeType(const std::string& path) override {
@@ -450,7 +452,7 @@ void BaseWebUIBrowserTest::SetUpOnMainThread() {
content::WebUIControllerFactory::RegisterFactory(test_factory_.get()); content::WebUIControllerFactory::RegisterFactory(test_factory_.get());
test_factory_->AddFactoryOverride(GURL(kDummyURL).host(), test_factory_->AddFactoryOverride(DummyUrl().host(),
mock_provider_.Pointer()); mock_provider_.Pointer());
test_factory_->AddFactoryOverride(content::kChromeUIResourcesHost, test_factory_->AddFactoryOverride(content::kChromeUIResourcesHost,
mock_provider_.Pointer()); mock_provider_.Pointer());
@@ -459,7 +461,7 @@ void BaseWebUIBrowserTest::SetUpOnMainThread() {
void BaseWebUIBrowserTest::TearDownOnMainThread() { void BaseWebUIBrowserTest::TearDownOnMainThread() {
logging::SetLogMessageHandler(nullptr); logging::SetLogMessageHandler(nullptr);
test_factory_->RemoveFactoryOverride(GURL(kDummyURL).host()); test_factory_->RemoveFactoryOverride(DummyUrl().host());
content::WebUIControllerFactory::UnregisterFactoryForTesting( content::WebUIControllerFactory::UnregisterFactoryForTesting(
test_factory_.get()); test_factory_.get());

@@ -21,6 +21,13 @@
using content::WebUIMessageHandler; using content::WebUIMessageHandler;
namespace {
const GURL& DummyUrl() {
static GURL url(content::GetWebUIURLString("DummyURL"));
return url;
}
} // namespace
// According to the interface for EXPECT_FATAL_FAILURE // According to the interface for EXPECT_FATAL_FAILURE
// (https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#catching-failures) // (https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#catching-failures)
// the statement must be statically available. Therefore, we make a static // the statement must be statically available. Therefore, we make a static
@@ -79,7 +86,7 @@ IN_PROC_BROWSER_TEST_F(WebUIBrowserExpectFailTest, MAYBE_TestFailsFast) {
IN_PROC_BROWSER_TEST_F(WebUIBrowserExpectFailTest, IN_PROC_BROWSER_TEST_F(WebUIBrowserExpectFailTest,
MAYBE_TestRuntimeErrorFailsFast) { MAYBE_TestRuntimeErrorFailsFast) {
AddLibrary(base::FilePath(FILE_PATH_LITERAL("runtime_error.js"))); AddLibrary(base::FilePath(FILE_PATH_LITERAL("runtime_error.js")));
ui_test_utils::NavigateToURL(browser(), GURL(kDummyURL)); ui_test_utils::NavigateToURL(browser(), DummyUrl());
EXPECT_FATAL_FAILURE(RunJavascriptTestNoReturn("TestRuntimeErrorFailsFast"), EXPECT_FATAL_FAILURE(RunJavascriptTestNoReturn("TestRuntimeErrorFailsFast"),
"GetAsBoolean(&run_test_succeeded_)"); "GetAsBoolean(&run_test_succeeded_)");
} }
@@ -170,11 +177,11 @@ class WebUIBrowserAsyncTest : public WebUIBrowserTest {
return &message_handler_; return &message_handler_;
} }
// Set up and browse to kDummyURL for all tests. // Set up and browse to DummyUrl() for all tests.
void SetUpOnMainThread() override { void SetUpOnMainThread() override {
WebUIBrowserTest::SetUpOnMainThread(); WebUIBrowserTest::SetUpOnMainThread();
AddLibrary(base::FilePath(FILE_PATH_LITERAL("async.js"))); AddLibrary(base::FilePath(FILE_PATH_LITERAL("async.js")));
ui_test_utils::NavigateToURL(browser(), GURL(kDummyURL)); ui_test_utils::NavigateToURL(browser(), DummyUrl());
} }
DISALLOW_COPY_AND_ASSIGN(WebUIBrowserAsyncTest); DISALLOW_COPY_AND_ASSIGN(WebUIBrowserAsyncTest);

@@ -206,7 +206,7 @@ std::string DomDistillerViewerSource::GetSource() {
void DomDistillerViewerSource::StartDataRequest( void DomDistillerViewerSource::StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) { content::URLDataSource::GotDataCallback callback) {
// TODO(crbug/1009127): simplify path matching. // TODO(crbug/1009127): simplify path matching.
const std::string path = URLDataSource::URLToRequestPath(url); const std::string path = URLDataSource::URLToRequestPath(url);
content::WebContents* web_contents = wc_getter.Run(); content::WebContents* web_contents = wc_getter.Run();
@@ -214,12 +214,12 @@ void DomDistillerViewerSource::StartDataRequest(
return; return;
if (kViewerCssPath == path) { if (kViewerCssPath == path) {
std::string css = viewer::GetCss(); std::string css = viewer::GetCss();
callback.Run(base::RefCountedString::TakeString(&css)); std::move(callback).Run(base::RefCountedString::TakeString(&css));
return; return;
} }
if (kViewerLoadingImagePath == path) { if (kViewerLoadingImagePath == path) {
std::string image = viewer::GetLoadingImage(); std::string image = viewer::GetLoadingImage();
callback.Run(base::RefCountedString::TakeString(&image)); std::move(callback).Run(base::RefCountedString::TakeString(&image));
return; return;
} }
if (base::StartsWith(path, kViewerSaveFontScalingPath, if (base::StartsWith(path, kViewerSaveFontScalingPath,
@@ -267,7 +267,8 @@ void DomDistillerViewerSource::StartDataRequest(
} }
// Place template on the page. // Place template on the page.
callback.Run(base::RefCountedString::TakeString(&unsafe_page_html)); std::move(callback).Run(
base::RefCountedString::TakeString(&unsafe_page_html));
} }
std::string DomDistillerViewerSource::GetMimeType(const std::string& path) { std::string DomDistillerViewerSource::GetMimeType(const std::string& path) {

@@ -32,7 +32,7 @@ class DomDistillerViewerSource : public content::URLDataSource {
void StartDataRequest( void StartDataRequest(
const GURL& url, const GURL& url,
const content::WebContents::Getter& wc_getter, const content::WebContents::Getter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) override; content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override; std::string GetMimeType(const std::string& path) override;
bool ShouldServiceRequest(const GURL& url, bool ShouldServiceRequest(const GURL& url,
content::ResourceContext* resource_context, content::ResourceContext* resource_context,

@@ -48,13 +48,13 @@ int TracingManager::RequestTrace() {
return current_trace_id_; return current_trace_id_;
} }
bool TracingManager::GetTraceData(int id, const TraceDataCallback& callback) { bool TracingManager::GetTraceData(int id, TraceDataCallback callback) {
// If a trace is being collected currently, send it via callback when // If a trace is being collected currently, send it via callback when
// complete. // complete.
if (current_trace_id_) { if (current_trace_id_) {
// Only allow one trace data request at a time. // Only allow one trace data request at a time.
if (trace_callback_.is_null()) { if (!trace_callback_) {
trace_callback_ = callback; trace_callback_ = std::move(callback);
return true; return true;
} else { } else {
return false; return false;
@@ -66,7 +66,7 @@ bool TracingManager::GetTraceData(int id, const TraceDataCallback& callback) {
// Always return the data asychronously, so the behavior is consistant. // Always return the data asychronously, so the behavior is consistant.
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(callback, data->second)); FROM_HERE, base::BindOnce(std::move(callback), data->second));
return true; return true;
} }
} }
@@ -79,10 +79,8 @@ void TracingManager::DiscardTraceData(int id) {
current_trace_id_ = 0; current_trace_id_ = 0;
// If the trace has already been requested, provide an empty string. // If the trace has already been requested, provide an empty string.
if (!trace_callback_.is_null()) { if (trace_callback_)
trace_callback_.Run(scoped_refptr<base::RefCountedString>()); std::move(trace_callback_).Run(scoped_refptr<base::RefCountedString>());
trace_callback_.Reset();
}
} }
} }
@@ -106,10 +104,8 @@ void TracingManager::OnTraceDataCollected(
trace_data_[current_trace_id_] = output; trace_data_[current_trace_id_] = output;
if (!trace_callback_.is_null()) { if (trace_callback_)
trace_callback_.Run(output); std::move(trace_callback_).Run(output);
trace_callback_.Reset();
}
current_trace_id_ = 0; current_trace_id_ = 0;

@@ -20,8 +20,8 @@ class RefCountedString;
} }
// Callback used for getting the output of a trace. // Callback used for getting the output of a trace.
typedef base::Callback<void(scoped_refptr<base::RefCountedString> trace_data)> using TraceDataCallback =
TraceDataCallback; base::OnceCallback<void(scoped_refptr<base::RefCountedString> trace_data)>;
// This class is used to manage performance metrics that can be attached to // This class is used to manage performance metrics that can be attached to
// feedback reports. This class is a Singleton that is owned by the preference // feedback reports. This class is a Singleton that is owned by the preference
@@ -49,7 +49,7 @@ class TracingManager {
// Get the trace data for |id|. On success, true is returned, and the data is // Get the trace data for |id|. On success, true is returned, and the data is
// returned via |callback|. Returns false on failure. // returned via |callback|. Returns false on failure.
bool GetTraceData(int id, const TraceDataCallback& callback); bool GetTraceData(int id, TraceDataCallback callback);
// Discard the data for trace |id|. // Discard the data for trace |id|.
void DiscardTraceData(int id); void DiscardTraceData(int id);

@@ -34,9 +34,9 @@ void FakeGCMDriver::ValidateRegistration(
const std::string& app_id, const std::string& app_id,
const std::vector<std::string>& sender_ids, const std::vector<std::string>& sender_ids,
const std::string& registration_id, const std::string& registration_id,
const ValidateRegistrationCallback& callback) { ValidateRegistrationCallback callback) {
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(callback, true /* is_valid */)); FROM_HERE, base::BindOnce(std::move(callback), true /* is_valid */));
} }
void FakeGCMDriver::OnSignedIn() { void FakeGCMDriver::OnSignedIn() {

@@ -26,11 +26,10 @@ class FakeGCMDriver : public GCMDriver {
~FakeGCMDriver() override; ~FakeGCMDriver() override;
// GCMDriver overrides: // GCMDriver overrides:
void ValidateRegistration( void ValidateRegistration(const std::string& app_id,
const std::string& app_id, const std::vector<std::string>& sender_ids,
const std::vector<std::string>& sender_ids, const std::string& registration_id,
const std::string& registration_id, ValidateRegistrationCallback callback) override;
const ValidateRegistrationCallback& callback) override;
void OnSignedIn() override; void OnSignedIn() override;
void OnSignedOut() override; void OnSignedOut() override;
void AddConnectionObserver(GCMConnectionObserver* observer) override; void AddConnectionObserver(GCMConnectionObserver* observer) override;

@@ -44,7 +44,7 @@ class InstanceIDHandler {
public: public:
using GetTokenCallback = base::OnceCallback<void(const std::string& token, using GetTokenCallback = base::OnceCallback<void(const std::string& token,
GCMClient::Result result)>; GCMClient::Result result)>;
using ValidateTokenCallback = base::Callback<void(bool is_valid)>; using ValidateTokenCallback = base::OnceCallback<void(bool is_valid)>;
using DeleteTokenCallback = using DeleteTokenCallback =
base::OnceCallback<void(GCMClient::Result result)>; base::OnceCallback<void(GCMClient::Result result)>;
using GetInstanceIDDataCallback = using GetInstanceIDDataCallback =
@@ -64,7 +64,7 @@ class InstanceIDHandler {
const std::string& authorized_entity, const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) = 0; ValidateTokenCallback callback) = 0;
virtual void DeleteToken(const std::string& app_id, virtual void DeleteToken(const std::string& app_id,
const std::string& authorized_entity, const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
@@ -95,7 +95,7 @@ class GCMDriver {
using RegisterCallback = using RegisterCallback =
base::OnceCallback<void(const std::string& registration_id, base::OnceCallback<void(const std::string& registration_id,
GCMClient::Result result)>; GCMClient::Result result)>;
using ValidateRegistrationCallback = base::Callback<void(bool is_valid)>; using ValidateRegistrationCallback = base::OnceCallback<void(bool is_valid)>;
using UnregisterCallback = base::OnceCallback<void(GCMClient::Result result)>; using UnregisterCallback = base::OnceCallback<void(GCMClient::Result result)>;
using SendCallback = base::Callback<void(const std::string& message_id, using SendCallback = base::Callback<void(const std::string& message_id,
GCMClient::Result result)>; GCMClient::Result result)>;
@@ -131,11 +131,10 @@ class GCMDriver {
// Checks that the provided |sender_ids| and |registration_id| matches the // Checks that the provided |sender_ids| and |registration_id| matches the
// stored registration info for |app_id|. // stored registration info for |app_id|.
virtual void ValidateRegistration( virtual void ValidateRegistration(const std::string& app_id,
const std::string& app_id, const std::vector<std::string>& sender_ids,
const std::vector<std::string>& sender_ids, const std::string& registration_id,
const std::string& registration_id, ValidateRegistrationCallback callback) = 0;
const ValidateRegistrationCallback& callback) = 0;
// Unregisters all sender_ids for an app. Only works on non-Android. Will also // Unregisters all sender_ids for an app. Only works on non-Android. Will also
// remove any encryption keys associated with the |app_id|. // remove any encryption keys associated with the |app_id|.

@@ -119,10 +119,10 @@ void GCMDriverAndroid::ValidateRegistration(
const std::string& app_id, const std::string& app_id,
const std::vector<std::string>& sender_ids, const std::vector<std::string>& sender_ids,
const std::string& registration_id, const std::string& registration_id,
const ValidateRegistrationCallback& callback) { ValidateRegistrationCallback callback) {
// gcm_driver doesn't store registration IDs on Android, so assume it's valid. // gcm_driver doesn't store registration IDs on Android, so assume it's valid.
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(callback, true /* is_valid */)); FROM_HERE, base::BindOnce(std::move(callback), true /* is_valid */));
} }
void GCMDriverAndroid::OnSignedIn() { void GCMDriverAndroid::OnSignedIn() {

@@ -58,11 +58,10 @@ class GCMDriverAndroid : public GCMDriver,
const base::android::JavaParamRef<jobjectArray>& data_keys_and_values); const base::android::JavaParamRef<jobjectArray>& data_keys_and_values);
// GCMDriver implementation: // GCMDriver implementation:
void ValidateRegistration( void ValidateRegistration(const std::string& app_id,
const std::string& app_id, const std::vector<std::string>& sender_ids,
const std::vector<std::string>& sender_ids, const std::string& registration_id,
const std::string& registration_id, ValidateRegistrationCallback callback) override;
const ValidateRegistrationCallback& callback) override;
void OnSignedIn() override; void OnSignedIn() override;
void OnSignedOut() override; void OnSignedOut() override;
void Enable() override; void Enable() override;

@@ -563,7 +563,7 @@ void GCMDriverDesktop::ValidateRegistration(
const std::string& app_id, const std::string& app_id,
const std::vector<std::string>& sender_ids, const std::vector<std::string>& sender_ids,
const std::string& registration_id, const std::string& registration_id,
const ValidateRegistrationCallback& callback) { ValidateRegistrationCallback callback) {
DCHECK(!app_id.empty()); DCHECK(!app_id.empty());
DCHECK(!sender_ids.empty() && sender_ids.size() <= kMaxSenders); DCHECK(!sender_ids.empty() && sender_ids.size() <= kMaxSenders);
DCHECK(!registration_id.empty()); DCHECK(!registration_id.empty());
@@ -586,25 +586,27 @@ void GCMDriverDesktop::ValidateRegistration(
std::sort(gcm_info->sender_ids.begin(), gcm_info->sender_ids.end()); std::sort(gcm_info->sender_ids.begin(), gcm_info->sender_ids.end());
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
delayed_task_controller_->AddTask(base::Bind( delayed_task_controller_->AddTask(
&GCMDriverDesktop::DoValidateRegistration, base::BindOnce(&GCMDriverDesktop::DoValidateRegistration,
weak_ptr_factory_.GetWeakPtr(), gcm_info, registration_id, callback)); weak_ptr_factory_.GetWeakPtr(), gcm_info,
registration_id, std::move(callback)));
return; return;
} }
DoValidateRegistration(std::move(gcm_info), registration_id, callback); DoValidateRegistration(std::move(gcm_info), registration_id,
std::move(callback));
} }
void GCMDriverDesktop::DoValidateRegistration( void GCMDriverDesktop::DoValidateRegistration(
scoped_refptr<RegistrationInfo> registration_info, scoped_refptr<RegistrationInfo> registration_info,
const std::string& registration_id, const std::string& registration_id,
const ValidateRegistrationCallback& callback) { ValidateRegistrationCallback callback) {
base::PostTaskAndReplyWithResult( base::PostTaskAndReplyWithResult(
io_thread_.get(), FROM_HERE, io_thread_.get(), FROM_HERE,
base::Bind(&GCMDriverDesktop::IOWorker::ValidateRegistration, base::BindOnce(&GCMDriverDesktop::IOWorker::ValidateRegistration,
base::Unretained(io_worker_.get()), base::Unretained(io_worker_.get()),
std::move(registration_info), registration_id), std::move(registration_info), registration_id),
callback); std::move(callback));
} }
void GCMDriverDesktop::Shutdown() { void GCMDriverDesktop::Shutdown() {
@@ -928,12 +930,12 @@ void GCMDriverDesktop::ValidateToken(const std::string& app_id,
const std::string& authorized_entity, const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) { ValidateTokenCallback callback) {
DCHECK(!app_id.empty()); DCHECK(!app_id.empty());
DCHECK(!authorized_entity.empty()); DCHECK(!authorized_entity.empty());
DCHECK(!scope.empty()); DCHECK(!scope.empty());
DCHECK(!token.empty()); DCHECK(!token.empty());
DCHECK(!callback.is_null()); DCHECK(callback);
DCHECK(ui_thread_->RunsTasksInCurrentSequence()); DCHECK(ui_thread_->RunsTasksInCurrentSequence());
GCMClient::Result result = EnsureStarted(GCMClient::IMMEDIATE_START); GCMClient::Result result = EnsureStarted(GCMClient::IMMEDIATE_START);
@@ -953,13 +955,15 @@ void GCMDriverDesktop::ValidateToken(const std::string& app_id,
instance_id_info->scope = scope; instance_id_info->scope = scope;
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
delayed_task_controller_->AddTask(base::Bind( delayed_task_controller_->AddTask(
&GCMDriverDesktop::DoValidateRegistration, base::BindOnce(&GCMDriverDesktop::DoValidateRegistration,
weak_ptr_factory_.GetWeakPtr(), instance_id_info, token, callback)); weak_ptr_factory_.GetWeakPtr(), instance_id_info, token,
std::move(callback)));
return; return;
} }
DoValidateRegistration(std::move(instance_id_info), token, callback); DoValidateRegistration(std::move(instance_id_info), token,
std::move(callback));
} }
void GCMDriverDesktop::DeleteToken(const std::string& app_id, void GCMDriverDesktop::DeleteToken(const std::string& app_id,
@@ -993,12 +997,9 @@ void GCMDriverDesktop::DeleteToken(const std::string& app_id,
// Delay the DeleteToken operation until GCMClient is ready. // Delay the DeleteToken operation until GCMClient is ready.
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
delayed_task_controller_->AddTask( delayed_task_controller_->AddTask(base::BindOnce(
base::Bind(&GCMDriverDesktop::DoDeleteToken, &GCMDriverDesktop::DoDeleteToken, weak_ptr_factory_.GetWeakPtr(),
weak_ptr_factory_.GetWeakPtr(), app_id, authorized_entity, scope));
app_id,
authorized_entity,
scope));
return; return;
} }
@@ -1031,12 +1032,9 @@ void GCMDriverDesktop::AddInstanceIDData(
// Delay the operation until GCMClient is ready. // Delay the operation until GCMClient is ready.
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
delayed_task_controller_->AddTask( delayed_task_controller_->AddTask(base::BindOnce(
base::Bind(&GCMDriverDesktop::DoAddInstanceIDData, &GCMDriverDesktop::DoAddInstanceIDData, weak_ptr_factory_.GetWeakPtr(),
weak_ptr_factory_.GetWeakPtr(), app_id, instance_id, extra_data));
app_id,
instance_id,
extra_data));
return; return;
} }
@@ -1066,9 +1064,8 @@ void GCMDriverDesktop::RemoveInstanceIDData(const std::string& app_id) {
// Delay the operation until GCMClient is ready. // Delay the operation until GCMClient is ready.
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
delayed_task_controller_->AddTask( delayed_task_controller_->AddTask(
base::Bind(&GCMDriverDesktop::DoRemoveInstanceIDData, base::BindOnce(&GCMDriverDesktop::DoRemoveInstanceIDData,
weak_ptr_factory_.GetWeakPtr(), weak_ptr_factory_.GetWeakPtr(), app_id));
app_id));
return; return;
} }
@@ -1110,9 +1107,8 @@ void GCMDriverDesktop::GetInstanceIDData(
// Delay the operation until GCMClient is ready. // Delay the operation until GCMClient is ready.
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
delayed_task_controller_->AddTask( delayed_task_controller_->AddTask(
base::Bind(&GCMDriverDesktop::DoGetInstanceIDData, base::BindOnce(&GCMDriverDesktop::DoGetInstanceIDData,
weak_ptr_factory_.GetWeakPtr(), weak_ptr_factory_.GetWeakPtr(), app_id));
app_id));
return; return;
} }
@@ -1178,10 +1174,9 @@ void GCMDriverDesktop::WakeFromSuspendForHeartbeat(bool wake) {
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
// The GCM service was initialized but has not started yet. // The GCM service was initialized but has not started yet.
delayed_task_controller_->AddTask( delayed_task_controller_->AddTask(base::BindOnce(
base::Bind(&GCMDriverDesktop::WakeFromSuspendForHeartbeat, &GCMDriverDesktop::WakeFromSuspendForHeartbeat,
weak_ptr_factory_.GetWeakPtr(), weak_ptr_factory_.GetWeakPtr(), wake_from_suspend_enabled_));
wake_from_suspend_enabled_));
return; return;
} }
@@ -1205,8 +1200,8 @@ void GCMDriverDesktop::AddHeartbeatInterval(const std::string& scope,
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
// The GCM service was initialized but has not started yet. // The GCM service was initialized but has not started yet.
delayed_task_controller_->AddTask( delayed_task_controller_->AddTask(
base::Bind(&GCMDriverDesktop::AddHeartbeatInterval, base::BindOnce(&GCMDriverDesktop::AddHeartbeatInterval,
weak_ptr_factory_.GetWeakPtr(), scope, interval_ms)); weak_ptr_factory_.GetWeakPtr(), scope, interval_ms));
return; return;
} }
@@ -1226,8 +1221,8 @@ void GCMDriverDesktop::RemoveHeartbeatInterval(const std::string& scope) {
if (!delayed_task_controller_->CanRunTaskWithoutDelay()) { if (!delayed_task_controller_->CanRunTaskWithoutDelay()) {
// The GCM service was initialized but has not started yet. // The GCM service was initialized but has not started yet.
delayed_task_controller_->AddTask( delayed_task_controller_->AddTask(
base::Bind(&GCMDriverDesktop::RemoveHeartbeatInterval, base::BindOnce(&GCMDriverDesktop::RemoveHeartbeatInterval,
weak_ptr_factory_.GetWeakPtr(), scope)); weak_ptr_factory_.GetWeakPtr(), scope));
return; return;
} }

@@ -67,11 +67,10 @@ class GCMDriverDesktop : public GCMDriver,
~GCMDriverDesktop() override; ~GCMDriverDesktop() override;
// GCMDriver implementation: // GCMDriver implementation:
void ValidateRegistration( void ValidateRegistration(const std::string& app_id,
const std::string& app_id, const std::vector<std::string>& sender_ids,
const std::vector<std::string>& sender_ids, const std::string& registration_id,
const std::string& registration_id, ValidateRegistrationCallback callback) override;
const ValidateRegistrationCallback& callback) override;
void Shutdown() override; void Shutdown() override;
void OnSignedIn() override; void OnSignedIn() override;
void OnSignedOut() override; void OnSignedOut() override;
@@ -128,7 +127,7 @@ class GCMDriverDesktop : public GCMDriver,
const std::string& authorized_entity, const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) override; ValidateTokenCallback callback) override;
void DeleteToken(const std::string& app_id, void DeleteToken(const std::string& app_id,
const std::string& authorized_entity, const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
@@ -150,7 +149,7 @@ class GCMDriverDesktop : public GCMDriver,
void DoValidateRegistration(scoped_refptr<RegistrationInfo> registration_info, void DoValidateRegistration(scoped_refptr<RegistrationInfo> registration_info,
const std::string& registration_id, const std::string& registration_id,
const ValidateRegistrationCallback& callback); ValidateRegistrationCallback callback);
// Stops the GCM service. It can be restarted by calling EnsureStarted again. // Stops the GCM service. It can be restarted by calling EnsureStarted again.
void Stop(); void Stop();

@@ -85,9 +85,9 @@ void FakeGCMDriverForInstanceID::ValidateToken(
const std::string& authorized_entity, const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) { ValidateTokenCallback callback) {
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(callback, true /* is_valid */)); FROM_HERE, base::BindOnce(std::move(callback), true /* is_valid */));
} }
void FakeGCMDriverForInstanceID::DeleteToken( void FakeGCMDriverForInstanceID::DeleteToken(

@@ -51,7 +51,7 @@ class FakeGCMDriverForInstanceID : public gcm::FakeGCMDriver,
const std::string& authorized_entity, const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) override; ValidateTokenCallback callback) override;
void DeleteToken(const std::string& app_id, void DeleteToken(const std::string& app_id,
const std::string& authorized_entity, const std::string& authorized_entity,
const std::string& scope, const std::string& scope,

@@ -71,7 +71,7 @@ class InstanceID {
base::Callback<void(const base::Time& creation_time)>; base::Callback<void(const base::Time& creation_time)>;
using GetTokenCallback = using GetTokenCallback =
base::OnceCallback<void(const std::string& token, Result result)>; base::OnceCallback<void(const std::string& token, Result result)>;
using ValidateTokenCallback = base::Callback<void(bool is_valid)>; using ValidateTokenCallback = base::OnceCallback<void(bool is_valid)>;
using GetEncryptionInfoCallback = using GetEncryptionInfoCallback =
base::OnceCallback<void(std::string p256dh, std::string auth_secret)>; base::OnceCallback<void(std::string p256dh, std::string auth_secret)>;
using DeleteTokenCallback = base::OnceCallback<void(Result result)>; using DeleteTokenCallback = base::OnceCallback<void(Result result)>;
@@ -121,7 +121,7 @@ class InstanceID {
virtual void ValidateToken(const std::string& authorized_entity, virtual void ValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) = 0; ValidateTokenCallback callback) = 0;
// Get the public encryption key and authentication secret associated with a // Get the public encryption key and authentication secret associated with a
// GCM-scoped token. If encryption info is not yet associated, it will be // GCM-scoped token. If encryption info is not yet associated, it will be

@@ -125,10 +125,10 @@ void InstanceIDAndroid::GetToken(
void InstanceIDAndroid::ValidateToken(const std::string& authorized_entity, void InstanceIDAndroid::ValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) { ValidateTokenCallback callback) {
// gcm_driver doesn't store tokens on Android, so assume it's valid. // gcm_driver doesn't store tokens on Android, so assume it's valid.
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(callback, true /* is_valid */)); FROM_HERE, base::BindOnce(std::move(callback), true /* is_valid */));
} }
void InstanceIDAndroid::DeleteTokenImpl(const std::string& authorized_entity, void InstanceIDAndroid::DeleteTokenImpl(const std::string& authorized_entity,

@@ -51,7 +51,7 @@ class InstanceIDAndroid : public InstanceID {
void ValidateToken(const std::string& authorized_entity, void ValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) override; ValidateTokenCallback callback) override;
void DeleteTokenImpl(const std::string& audience, void DeleteTokenImpl(const std::string& audience,
const std::string& scope, const std::string& scope,
DeleteTokenCallback callback) override; DeleteTokenCallback callback) override;

@@ -118,26 +118,27 @@ void InstanceIDImpl::DoGetToken(
void InstanceIDImpl::ValidateToken(const std::string& authorized_entity, void InstanceIDImpl::ValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) { ValidateTokenCallback callback) {
DCHECK(!authorized_entity.empty()); DCHECK(!authorized_entity.empty());
DCHECK(!scope.empty()); DCHECK(!scope.empty());
DCHECK(!token.empty()); DCHECK(!token.empty());
RunWhenReady(base::BindOnce(&InstanceIDImpl::DoValidateToken, RunWhenReady(base::BindOnce(&InstanceIDImpl::DoValidateToken,
weak_ptr_factory_.GetWeakPtr(), authorized_entity, weak_ptr_factory_.GetWeakPtr(), authorized_entity,
scope, token, callback)); scope, token, std::move(callback)));
} }
void InstanceIDImpl::DoValidateToken(const std::string& authorized_entity, void InstanceIDImpl::DoValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) { ValidateTokenCallback callback) {
if (id_.empty()) { if (id_.empty()) {
callback.Run(false /* is_valid */); std::move(callback).Run(false /* is_valid */);
return; return;
} }
Handler()->ValidateToken(app_id(), authorized_entity, scope, token, callback); Handler()->ValidateToken(app_id(), authorized_entity, scope, token,
std::move(callback));
} }
void InstanceIDImpl::DeleteTokenImpl(const std::string& authorized_entity, void InstanceIDImpl::DeleteTokenImpl(const std::string& authorized_entity,

@@ -41,7 +41,7 @@ class InstanceIDImpl : public InstanceID {
void ValidateToken(const std::string& authorized_entity, void ValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback) override; ValidateTokenCallback callback) override;
void DeleteTokenImpl(const std::string& authorized_entity, void DeleteTokenImpl(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
DeleteTokenCallback callback) override; DeleteTokenCallback callback) override;
@@ -69,7 +69,7 @@ class InstanceIDImpl : public InstanceID {
void DoValidateToken(const std::string& authorized_entity, void DoValidateToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback); ValidateTokenCallback callback);
void DoDeleteToken(const std::string& authorized_entity, void DoDeleteToken(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
DeleteTokenCallback callback); DeleteTokenCallback callback);

@@ -103,11 +103,17 @@ class MockInstanceID : public InstanceID {
const std::map<std::string, std::string>& options, const std::map<std::string, std::string>& options,
std::set<Flags> flags, std::set<Flags> flags,
GetTokenCallback& callback)); GetTokenCallback& callback));
MOCK_METHOD4(ValidateToken, void ValidateToken(const std::string& authorized_entity,
const std::string& scope,
const std::string& token,
ValidateTokenCallback callback) override {
ValidateToken_(authorized_entity, scope, token, callback);
}
MOCK_METHOD4(ValidateToken_,
void(const std::string& authorized_entity, void(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback)); ValidateTokenCallback& callback));
protected: protected:
void DeleteTokenImpl(const std::string& authorized_entity, void DeleteTokenImpl(const std::string& authorized_entity,

@@ -77,11 +77,17 @@ class MockInstanceID : public InstanceID {
const std::map<std::string, std::string>& options, const std::map<std::string, std::string>& options,
std::set<Flags> flags, std::set<Flags> flags,
GetTokenCallback& callback)); GetTokenCallback& callback));
MOCK_METHOD4(ValidateToken, void ValidateToken(const std::string& authorized_entity,
const std::string& scope,
const std::string& token,
ValidateTokenCallback callback) override {
ValidateToken_(authorized_entity, scope, token, callback);
}
MOCK_METHOD4(ValidateToken_,
void(const std::string& authorized_entity, void(const std::string& authorized_entity,
const std::string& scope, const std::string& scope,
const std::string& token, const std::string& token,
const ValidateTokenCallback& callback)); ValidateTokenCallback& callback));
protected: protected:
void DeleteTokenImpl(const std::string& authorized_entity, void DeleteTokenImpl(const std::string& authorized_entity,
@@ -112,11 +118,17 @@ class MockGCMDriver : public gcm::GCMDriver {
&test_url_loader_factory_)) {} &test_url_loader_factory_)) {}
~MockGCMDriver() override = default; ~MockGCMDriver() override = default;
MOCK_METHOD4(ValidateRegistration, void ValidateRegistration(const std::string& app_id,
const std::vector<std::string>& sender_ids,
const std::string& registration_id,
ValidateRegistrationCallback callback) override {
ValidateRegistration_(app_id, sender_ids, registration_id, callback);
}
MOCK_METHOD4(ValidateRegistration_,
void(const std::string& app_id, void(const std::string& app_id,
const std::vector<std::string>& sender_ids, const std::vector<std::string>& sender_ids,
const std::string& registration_id, const std::string& registration_id,
const ValidateRegistrationCallback& callback)); ValidateRegistrationCallback& callback));
MOCK_METHOD0(OnSignedIn, void()); MOCK_METHOD0(OnSignedIn, void());
MOCK_METHOD0(OnSignedOut, void()); MOCK_METHOD0(OnSignedOut, void());
MOCK_METHOD1(AddConnectionObserver, MOCK_METHOD1(AddConnectionObserver,
@@ -438,7 +450,7 @@ TEST_F(FCMNetworkHandlerTest, ShouldScheduleTokenValidationAndActOnNewToken) {
EXPECT_CALL(*mock_instance_id(), GetToken_(_, _, _, _, _)) EXPECT_CALL(*mock_instance_id(), GetToken_(_, _, _, _, _))
.WillOnce( .WillOnce(
InvokeCallbackArgument<4>("token", InstanceID::Result::SUCCESS)); InvokeCallbackArgument<4>("token", InstanceID::Result::SUCCESS));
EXPECT_CALL(*mock_instance_id(), ValidateToken(_, _, _, _)).Times(0); EXPECT_CALL(*mock_instance_id(), ValidateToken_(_, _, _, _)).Times(0);
EXPECT_CALL(mock_on_token_callback, Run("token")).Times(1); EXPECT_CALL(mock_on_token_callback, Run("token")).Times(1);
handler->StartListening(); handler->StartListening();
testing::Mock::VerifyAndClearExpectations(mock_instance_id()); testing::Mock::VerifyAndClearExpectations(mock_instance_id());
@@ -469,7 +481,7 @@ TEST_F(FCMNetworkHandlerTest,
EXPECT_CALL(*mock_instance_id(), GetToken_(_, _, _, _, _)) EXPECT_CALL(*mock_instance_id(), GetToken_(_, _, _, _, _))
.WillOnce( .WillOnce(
InvokeCallbackArgument<4>("token", InstanceID::Result::SUCCESS)); InvokeCallbackArgument<4>("token", InstanceID::Result::SUCCESS));
EXPECT_CALL(*mock_instance_id(), ValidateToken(_, _, _, _)).Times(0); EXPECT_CALL(*mock_instance_id(), ValidateToken_(_, _, _, _)).Times(0);
EXPECT_CALL(mock_on_token_callback, Run("token")).Times(1); EXPECT_CALL(mock_on_token_callback, Run("token")).Times(1);
handler->StartListening(); handler->StartListening();
testing::Mock::VerifyAndClearExpectations(mock_instance_id()); testing::Mock::VerifyAndClearExpectations(mock_instance_id());

@@ -105,15 +105,15 @@ void IndexedDBBlobInfo::set_key(int64_t key) {
} }
void IndexedDBBlobInfo::set_mark_used_callback( void IndexedDBBlobInfo::set_mark_used_callback(
const base::Closure& mark_used_callback) { base::RepeatingClosure mark_used_callback) {
DCHECK(mark_used_callback_.is_null()); DCHECK(!mark_used_callback_);
mark_used_callback_ = mark_used_callback; mark_used_callback_ = std::move(mark_used_callback);
} }
void IndexedDBBlobInfo::set_release_callback( void IndexedDBBlobInfo::set_release_callback(
const base::RepeatingClosure& release_callback) { base::RepeatingClosure release_callback) {
DCHECK(release_callback_.is_null()); DCHECK(!release_callback_);
release_callback_ = release_callback; release_callback_ = std::move(release_callback);
} }
} // namespace content } // namespace content

@@ -68,8 +68,8 @@ class CONTENT_EXPORT IndexedDBBlobInfo {
void set_file_path(const base::FilePath& file_path); void set_file_path(const base::FilePath& file_path);
void set_last_modified(const base::Time& time); void set_last_modified(const base::Time& time);
void set_key(int64_t key); void set_key(int64_t key);
void set_mark_used_callback(const base::RepeatingClosure& mark_used_callback); void set_mark_used_callback(base::RepeatingClosure mark_used_callback);
void set_release_callback(const base::RepeatingClosure& release_callback); void set_release_callback(base::RepeatingClosure release_callback);
private: private:
bool is_file_; bool is_file_;

@@ -14,6 +14,7 @@
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h" #include "base/task/post_task.h"
#include "base/test/bind_test_util.h" #include "base/test/bind_test_util.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/mock_callback.h" #include "base/test/mock_callback.h"
#include "base/test/test_simple_task_runner.h" #include "base/test/test_simple_task_runner.h"
#include "base/threading/thread.h" #include "base/threading/thread.h"
@@ -43,6 +44,7 @@
#include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom.h" #include "third_party/blink/public/mojom/indexeddb/indexeddb.mojom.h"
#include "url/origin.h" #include "url/origin.h"
using base::test::RunClosure;
using blink::IndexedDBDatabaseMetadata; using blink::IndexedDBDatabaseMetadata;
using blink::IndexedDBIndexKeys; using blink::IndexedDBIndexKeys;
using blink::IndexedDBKey; using blink::IndexedDBKey;
@@ -65,10 +67,6 @@ ACTION_TEMPLATE(MoveArg,
*out = std::move(*::testing::get<k>(args)); *out = std::move(*::testing::get<k>(args));
} }
ACTION_P(RunClosure, closure) {
closure.Run();
}
ACTION_P(QuitLoop, run_loop) { ACTION_P(QuitLoop, run_loop) {
run_loop->Quit(); run_loop->Quit();
} }
@@ -84,8 +82,6 @@ MATCHER_P(MatchesIDBKey, key, "") {
return arg.Equals(key); return arg.Equals(key);
} }
typedef void (base::Closure::*ClosureRunFcn)() const &;
static const char kDatabaseName[] = "db"; static const char kDatabaseName[] = "db";
static const char kOrigin[] = "https://www.example.com"; static const char kOrigin[] = "https://www.example.com";
static const int kFakeProcessId = 2; static const int kFakeProcessId = 2;
@@ -141,11 +137,11 @@ struct TestDatabaseConnection {
DISALLOW_COPY_AND_ASSIGN(TestDatabaseConnection); DISALLOW_COPY_AND_ASSIGN(TestDatabaseConnection);
}; };
void StatusCallback(const base::Closure& callback, void StatusCallback(base::OnceClosure callback,
blink::mojom::IDBStatus* status_out, blink::mojom::IDBStatus* status_out,
blink::mojom::IDBStatus status) { blink::mojom::IDBStatus status) {
*status_out = status; *status_out = status;
callback.Run(); std::move(callback).Run();
} }
class TestIndexedDBObserver : public IndexedDBContextImpl::Observer { class TestIndexedDBObserver : public IndexedDBContextImpl::Observer {
@@ -1051,7 +1047,8 @@ TEST_F(IndexedDBDispatcherHostTest, DISABLED_NotifyIndexedDBListChanged) {
{ {
::testing::InSequence dummy; ::testing::InSequence dummy;
base::RunLoop loop; base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(2, loop.QuitClosure()); base::RepeatingClosure quit_closure =
base::BarrierClosure(2, loop.QuitClosure());
EXPECT_CALL(*connection1.connection_callbacks, Complete(kTransactionId1)) EXPECT_CALL(*connection1.connection_callbacks, Complete(kTransactionId1))
.Times(1) .Times(1)
@@ -1107,7 +1104,8 @@ TEST_F(IndexedDBDispatcherHostTest, DISABLED_NotifyIndexedDBListChanged) {
{ {
::testing::InSequence dummy; ::testing::InSequence dummy;
base::RunLoop loop; base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(2, loop.QuitClosure()); base::RepeatingClosure quit_closure =
base::BarrierClosure(2, loop.QuitClosure());
EXPECT_CALL(*connection2.connection_callbacks, Complete(kTransactionId2)) EXPECT_CALL(*connection2.connection_callbacks, Complete(kTransactionId2))
.Times(1) .Times(1)
@@ -1159,7 +1157,8 @@ TEST_F(IndexedDBDispatcherHostTest, DISABLED_NotifyIndexedDBListChanged) {
{ {
::testing::InSequence dummy; ::testing::InSequence dummy;
base::RunLoop loop; base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(2, loop.QuitClosure()); base::RepeatingClosure quit_closure =
base::BarrierClosure(2, loop.QuitClosure());
EXPECT_CALL(*connection3.connection_callbacks, Complete(kTransactionId3)) EXPECT_CALL(*connection3.connection_callbacks, Complete(kTransactionId3))
.Times(1) .Times(1)

@@ -755,12 +755,12 @@ class RequestDataBrowserTest : public ContentBrowserTest {
base::AutoLock auto_lock(requests_lock_); base::AutoLock auto_lock(requests_lock_);
requests_.push_back(data); requests_.push_back(data);
if (requests_closure_) if (requests_closure_)
requests_closure_.Run(); std::move(requests_closure_).Run();
} }
base::Lock requests_lock_; base::Lock requests_lock_;
std::vector<RequestData> requests_; std::vector<RequestData> requests_;
base::Closure requests_closure_; base::OnceClosure requests_closure_;
std::unique_ptr<URLLoaderInterceptor> interceptor_; std::unique_ptr<URLLoaderInterceptor> interceptor_;
}; };

@@ -1137,7 +1137,7 @@ class NavigationURLLoaderImpl::URLLoaderRequestController
GlobalRequestID global_request_id_; GlobalRequestID global_request_id_;
net::RedirectInfo redirect_info_; net::RedirectInfo redirect_info_;
int redirect_limit_ = net::URLRequest::kMaxRedirects; int redirect_limit_ = net::URLRequest::kMaxRedirects;
base::Callback<WebContents*()> web_contents_getter_; base::RepeatingCallback<WebContents*()> web_contents_getter_;
std::unique_ptr<NavigationUIData> navigation_ui_data_; std::unique_ptr<NavigationUIData> navigation_ui_data_;
scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory_; scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory_;

@@ -61,17 +61,16 @@ bool ShouldHandleWebUIRequestCallback(const std::string& path) {
return path == kNetworkErrorDataFile; return path == kNetworkErrorDataFile;
} }
void HandleWebUIRequestCallback( void HandleWebUIRequestCallback(BrowserContext* current_context,
BrowserContext* current_context, const std::string& path,
const std::string& path, WebUIDataSource::GotDataCallback callback) {
const WebUIDataSource::GotDataCallback& callback) {
DCHECK(ShouldHandleWebUIRequestCallback(path)); DCHECK(ShouldHandleWebUIRequestCallback(path));
base::DictionaryValue data; base::DictionaryValue data;
data.Set(kErrorCodesDataName, GetNetworkErrorData()); data.Set(kErrorCodesDataName, GetNetworkErrorData());
std::string json_string; std::string json_string;
base::JSONWriter::Write(data, &json_string); base::JSONWriter::Write(data, &json_string);
callback.Run(base::RefCountedString::TakeString(&json_string)); std::move(callback).Run(base::RefCountedString::TakeString(&json_string));
} }
} // namespace } // namespace

@@ -79,14 +79,13 @@ class TestWebUIDataSource : public URLDataSource {
std::string GetSource() override { return "webui"; } std::string GetSource() override { return "webui"; }
void StartDataRequest( void StartDataRequest(const GURL& url,
const GURL& url, const WebContents::Getter& wc_getter,
const WebContents::Getter& wc_getter, URLDataSource::GotDataCallback callback) override {
const URLDataSource::GotDataCallback& callback) override {
std::string dummy_html = "<html><body>Foo</body></html>"; std::string dummy_html = "<html><body>Foo</body></html>";
scoped_refptr<base::RefCountedString> response = scoped_refptr<base::RefCountedString> response =
base::RefCountedString::TakeString(&dummy_html); base::RefCountedString::TakeString(&dummy_html);
callback.Run(response.get()); std::move(callback).Run(response.get());
} }
std::string GetMimeType(const std::string& path) override { std::string GetMimeType(const std::string& path) override {

Some files were not shown because too many files have changed in this diff Show More