Skip to content

Commit

Permalink
Show checkmark on current wallpaper search theme
Browse files Browse the repository at this point in the history
The goal is to be able to show if one of the current results shown is
the current background.
* Save wallpaper search result token to prefs when the background is
  set.
* Save the wallpaper search result to a file [token]background.jpg
* Include the token in the custom background info.
* Check in the UI that the image's token matches the token/id for the
  background info.

Also, added token to the removal of local background so that old
backgrounds with tokens don't pile up. When multiple are supported,
this can be changed, but I don't want unused background files to pile
up until then.

Screenshot: http://screenshot/AwN6N89Ng9Ehxmh

Bug: b/300971008
Change-Id: Ifcab988e00c557d55c23c369edee4f1951d1fbaa
Low-Coverage-Reason: TRIVIAL_CHANGE The changes to untrusted_source.cc are pretty trivial.
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4974862
Commit-Queue: Riley Tatum <rtatum@google.com>
Reviewed-by: Alex Gough <ajgo@chromium.org>
Reviewed-by: Tibor Goldschwendt <tiborg@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1215679}
  • Loading branch information
Riley Tatum authored and Chromium LUCI CQ committed Oct 26, 2023
1 parent 6472c2c commit b95536f
Show file tree
Hide file tree
Showing 13 changed files with 244 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,7 @@

.tile {
background-color: var(--color-sys-surface2);
border-radius: 12px;
outline-width: 0;
overflow: hidden;
place-self: stretch;
}

Expand All @@ -119,7 +117,20 @@
transform: translateX(-50%);
}

customize-chrome-check-mark-wrapper {
--customize-chrome-check-mark-wrapper-end: -4px;
--customize-chrome-check-mark-wrapper-size: 20px;
--customize-chrome-check-mark-wrapper-top: -6px;
}

customize-chrome-check-mark-wrapper[checked] .image-container {
padding-top: calc(100% - 4px);
width: calc(100% - 4px);
}

.image-container {
border-radius: 12px;
overflow: hidden;
padding-top: 100%;
position: relative;
width: 100%;
Expand Down Expand Up @@ -225,10 +236,13 @@ <h2 slot="heading">Wallpaper Search</h2>
<template is="dom-repeat" id="resultsRepeat" items="[[results_]]">
<div class="tile result" tabindex="0" role="button"
on-click="onResultClick_">
<div class="image-container">
<img src="data:image/png;base64,[[item.image]]">
</img>
</div>
<customize-chrome-check-mark-wrapper
checked="[[isBackgroundSelected_(item.id, theme_)]]">
<div class="image-container">
<img src="data:image/png;base64,[[item.image]]">
</img>
</div>
</customize-chrome-check-mark-wrapper>
</div>
</template>
<template is="dom-repeat" id="emptyRepeat" items="[[emptyContainers_]]">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import './check_mark_wrapper.js';
import './combobox/customize_chrome_combobox.js';
import 'chrome://customize-chrome-side-panel.top-chrome/shared/sp_heading.js';
import 'chrome://customize-chrome-side-panel.top-chrome/shared/sp_shared_style.css.js';
Expand All @@ -18,10 +19,11 @@ import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu
import {CrButtonElement} from 'chrome://resources/cr_elements/cr_button/cr_button.js';
import {assert} from 'chrome://resources/js/assert.js';
import {hexColorToSkColor} from 'chrome://resources/js/color_utils.js';
import {Token} from 'chrome://resources/mojo/mojo/public/mojom/base/token.mojom-webui.js';
import {DomRepeatEvent, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {CustomizeChromeCombobox} from './combobox/customize_chrome_combobox.js';
import {CustomizeChromePageHandlerInterface, DescriptorA, DescriptorDValue, Descriptors, WallpaperSearchResult} from './customize_chrome.mojom-webui.js';
import {CustomizeChromePageCallbackRouter, CustomizeChromePageHandlerInterface, DescriptorA, DescriptorDValue, Descriptors, Theme, WallpaperSearchResult} from './customize_chrome.mojom-webui.js';
import {CustomizeChromeApiProxy} from './customize_chrome_api_proxy.js';
import {getTemplate} from './wallpaper_search.html.js';

Expand Down Expand Up @@ -78,6 +80,10 @@ export class WallpaperSearchElement extends PolymerElement {
computed: 'computeSubmitBtnText_(results_)',
value: 'Search',
},
theme_: {
type: Object,
value: undefined,
},
};
}

Expand All @@ -91,11 +97,15 @@ export class WallpaperSearchElement extends PolymerElement {
private selectedDescriptorC_: string|null;
private selectedDescriptorD_: DescriptorDValue|null;
private submitBtnText_: string;
private theme_: Theme|undefined;

private callbackRouter_: CustomizeChromePageCallbackRouter;
private pageHandler_: CustomizeChromePageHandlerInterface;
private setThemeListenerId_: number|null = null;

constructor() {
super();
this.callbackRouter_ = CustomizeChromeApiProxy.getInstance().callbackRouter;
this.pageHandler_ = CustomizeChromeApiProxy.getInstance().handler;
this.pageHandler_.getDescriptors().then(({descriptors}) => {
if (descriptors) {
Expand All @@ -104,6 +114,21 @@ export class WallpaperSearchElement extends PolymerElement {
});
}

override connectedCallback() {
super.connectedCallback();
this.setThemeListenerId_ =
this.callbackRouter_.setTheme.addListener((theme: Theme) => {
this.theme_ = theme;
});
this.pageHandler_.updateTheme();
}

override disconnectedCallback() {
super.disconnectedCallback();
assert(this.setThemeListenerId_);
this.callbackRouter_.removeListener(this.setThemeListenerId_);
}

focusOnBackButton() {
this.$.heading.getBackButton().focus();
}
Expand All @@ -113,6 +138,14 @@ export class WallpaperSearchElement extends PolymerElement {
'Search';
}

private isBackgroundSelected_(id: Token): boolean {
return !!(
this.theme_ && this.theme_.backgroundImage &&
this.theme_.backgroundImage.localBackgroundId &&
this.theme_.backgroundImage.localBackgroundId.low === id.low &&
this.theme_.backgroundImage.localBackgroundId.high === id.high);
}

private async onBackClick_() {
this.dispatchEvent(new Event('back-click'));
}
Expand Down
5 changes: 5 additions & 0 deletions chrome/browser/search/background/ntp_background_data.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#include <string>

#include "base/token.h"
#include "chrome/browser/search/background/ntp_background.pb.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/skia/include/core/SkColor.h"
Expand Down Expand Up @@ -133,6 +134,10 @@ struct CustomBackground {
// Whether the image is a local resource.
bool is_uploaded_image;

// Id for local custom background. This can be empty if it is an uploaded
// local background, rather than from wallpaper search.
absl::optional<base::Token> local_background_id;

// First attribution string for custom background.
std::string custom_background_attribution_line_1;

Expand Down
88 changes: 66 additions & 22 deletions chrome/browser/search/background/ntp_custom_background_service.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "base/time/clock.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/token.h"
#include "base/values.h"
#include "chrome/browser/image_fetcher/image_decoder_impl.h"
#include "chrome/browser/profiles/profile.h"
Expand Down Expand Up @@ -120,11 +121,8 @@ void CopyFileToProfilePath(const base::FilePath& from_path,
chrome::kChromeUIUntrustedNewTabPageBackgroundFilename));
}

void WriteFileToProfilePath(const std::string& data,
const base::FilePath& profile_path) {
base::WriteFile(profile_path.AppendASCII(
chrome::kChromeUIUntrustedNewTabPageBackgroundFilename),
base::as_bytes(base::make_span(data)));
void WriteFileToPath(const std::string& data, const base::FilePath& path) {
base::WriteFile(path, base::as_bytes(base::make_span(data)));
}

std::string ReadFileToString(const base::FilePath& path) {
Expand All @@ -133,9 +131,10 @@ std::string ReadFileToString(const base::FilePath& path) {
return image_data;
}

void RemoveLocalBackgroundImageCopy(Profile* profile) {
void RemoveLocalBackgroundImageCopy(Profile* profile,
const std::string& file_prefix) {
base::FilePath path = profile->GetPath().AppendASCII(
chrome::kChromeUIUntrustedNewTabPageBackgroundFilename);
file_prefix + chrome::kChromeUIUntrustedNewTabPageBackgroundFilename);
base::ThreadPool::PostTask(
FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
base::GetDeleteFileCallback(path));
Expand All @@ -158,14 +157,18 @@ void NtpCustomBackgroundService::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
registry->RegisterBooleanPref(prefs::kNtpCustomBackgroundLocalToDevice,
false);
registry->RegisterStringPref(prefs::kNtpCustomBackgroundLocalToDeviceId, "");
}

// static
void NtpCustomBackgroundService::ResetProfilePrefs(Profile* profile) {
profile->GetPrefs()->ClearPref(prefs::kNtpCustomBackgroundDict);
profile->GetPrefs()->SetBoolean(prefs::kNtpCustomBackgroundLocalToDevice,
false);
RemoveLocalBackgroundImageCopy(profile);
auto* pref_service = profile->GetPrefs();
RemoveLocalBackgroundImageCopy(
profile,
pref_service->GetString(prefs::kNtpCustomBackgroundLocalToDeviceId));
pref_service->ClearPref(prefs::kNtpCustomBackgroundDict);
pref_service->SetBoolean(prefs::kNtpCustomBackgroundLocalToDevice, false);
pref_service->ClearPref(prefs::kNtpCustomBackgroundLocalToDeviceId);
}

NtpCustomBackgroundService::NtpCustomBackgroundService(Profile* profile)
Expand Down Expand Up @@ -237,8 +240,11 @@ void NtpCustomBackgroundService::OnNtpBackgroundServiceShuttingDown() {

void NtpCustomBackgroundService::UpdateBackgroundFromSync() {
// Any incoming change to synced background data should clear the local image.
RemoveLocalBackgroundImageCopy(
profile_,
pref_service_->GetString(prefs::kNtpCustomBackgroundLocalToDeviceId));
pref_service_->SetBoolean(prefs::kNtpCustomBackgroundLocalToDevice, false);
RemoveLocalBackgroundImageCopy(profile_);
pref_service_->ClearPref(prefs::kNtpCustomBackgroundLocalToDeviceId);
NotifyAboutBackgrounds();
}

Expand Down Expand Up @@ -277,8 +283,11 @@ void NtpCustomBackgroundService::SetCustomBackgroundInfo(
pref_service_->GetBoolean(prefs::kNtpCustomBackgroundLocalToDevice) &&
pref_service_->FindPreference(prefs::kNtpCustomBackgroundDict)
->IsDefaultValue();
RemoveLocalBackgroundImageCopy(
profile_,
pref_service_->GetString(prefs::kNtpCustomBackgroundLocalToDeviceId));
pref_service_->SetBoolean(prefs::kNtpCustomBackgroundLocalToDevice, false);
RemoveLocalBackgroundImageCopy(profile_);
pref_service_->ClearPref(prefs::kNtpCustomBackgroundLocalToDeviceId);

background_updated_timestamp_ = base::TimeTicks::Now();

Expand Down Expand Up @@ -370,13 +379,15 @@ void NtpCustomBackgroundService::SelectLocalBackgroundImage(
}

void NtpCustomBackgroundService::SetBackgroundToLocalResourceAndExtractColor(
const base::Token& id,
const SkBitmap& bitmap) {
NtpCustomBackgroundService::SetBackgroundToLocalResource();
NtpCustomBackgroundService::SetBackgroundToLocalResourceWithId(id);
NtpCustomBackgroundService::UpdateCustomLocalBackgroundColorAsync(
gfx::Image::CreateFrom1xBitmap(bitmap));
}

void NtpCustomBackgroundService::SelectLocalBackgroundImage(
const base::Token& id,
const SkBitmap& bitmap) {
if (IsCustomBackgroundDisabledByPolicy()) {
return;
Expand All @@ -391,12 +402,14 @@ void NtpCustomBackgroundService::SelectLocalBackgroundImage(
if (success) {
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()},
base::BindOnce(&WriteFileToProfilePath,
std::string(encoded.begin(), encoded.end()),
profile_->GetPath()),
base::BindOnce(
&WriteFileToPath, std::string(encoded.begin(), encoded.end()),
profile_->GetPath().AppendASCII(
id.ToString() +
chrome::kChromeUIUntrustedNewTabPageBackgroundFilename)),
base::BindOnce(&NtpCustomBackgroundService::
SetBackgroundToLocalResourceAndExtractColor,
weak_ptr_factory_.GetWeakPtr(), bitmap));
weak_ptr_factory_.GetWeakPtr(), id, bitmap));
}
}

Expand All @@ -408,7 +421,7 @@ void NtpCustomBackgroundService::RefreshBackgroundIfNeeded() {
}

const base::Value::Dict& background_info =
profile_->GetPrefs()->GetDict(prefs::kNtpCustomBackgroundDict);
pref_service_->GetDict(prefs::kNtpCustomBackgroundDict);
int64_t refresh_timestamp = 0;
const base::Value* timestamp_value =
background_info.Find(kNtpCustomBackgroundRefreshTimestamp);
Expand Down Expand Up @@ -452,10 +465,16 @@ NtpCustomBackgroundService::GetCustomBackground() {
// Add a timestamp to the url to prevent the browser from using a cached
// version when "Upload an image" is used multiple times.
std::string time_string = std::to_string(base::Time::Now().ToTimeT());
std::string local_string(chrome::kChromeUIUntrustedNewTabPageBackgroundUrl);
std::string local_background_id =
pref_service_->GetString(prefs::kNtpCustomBackgroundLocalToDeviceId);
std::string local_string(
chrome::kChromeUIUntrustedNewTabPageUrl + local_background_id +
chrome::kChromeUIUntrustedNewTabPageBackgroundFilename);
GURL timestamped_url(local_string + "?ts=" + time_string);
custom_background->custom_background_url = timestamped_url;
custom_background->is_uploaded_image = true;
custom_background->local_background_id =
base::Token::FromString(local_background_id);
custom_background->custom_background_snapshot_url = GURL();
custom_background->custom_background_attribution_line_1 = std::string();
custom_background->custom_background_attribution_line_2 = std::string();
Expand Down Expand Up @@ -611,15 +630,40 @@ void NtpCustomBackgroundService::VerifyCustomBackgroundImageURL() {

void NtpCustomBackgroundService::SetBackgroundToLocalResource() {
background_updated_timestamp_ = base::TimeTicks::Now();
// If the current background is a wallpaper search background, delete the
// file before setting the new background. This is temporary until multiple
// local images is supported.
if (pref_service_->GetBoolean(prefs::kNtpCustomBackgroundLocalToDevice) &&
!pref_service_->GetString(prefs::kNtpCustomBackgroundLocalToDeviceId)
.empty()) {
RemoveLocalBackgroundImageCopy(
profile_,
pref_service_->GetString(prefs::kNtpCustomBackgroundLocalToDeviceId));
}
pref_service_->SetBoolean(prefs::kNtpCustomBackgroundLocalToDevice, true);
pref_service_->ClearPref(prefs::kNtpCustomBackgroundLocalToDeviceId);
NotifyAboutBackgrounds();
}

void NtpCustomBackgroundService::SetBackgroundToLocalResourceWithId(
const base::Token& id) {
background_updated_timestamp_ = base::TimeTicks::Now();
// Remove the last local background if it exists. This is
// temporary until multiple local images is supported.
RemoveLocalBackgroundImageCopy(
profile_,
pref_service_->GetString(prefs::kNtpCustomBackgroundLocalToDeviceId));
pref_service_->SetBoolean(prefs::kNtpCustomBackgroundLocalToDevice, true);
pref_service_->SetString(prefs::kNtpCustomBackgroundLocalToDeviceId,
id.ToString());
NotifyAboutBackgrounds();
}

void NtpCustomBackgroundService::ForceRefreshBackground() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

const base::Value::Dict& background_info =
profile_->GetPrefs()->GetDict(prefs::kNtpCustomBackgroundDict);
pref_service_->GetDict(prefs::kNtpCustomBackgroundDict);
std::string collection_id =
background_info.Find(kNtpCustomBackgroundCollectionId)->GetString();
std::string resume_token =
Expand All @@ -630,7 +674,7 @@ void NtpCustomBackgroundService::ForceRefreshBackground() {
bool NtpCustomBackgroundService::IsCustomBackgroundPrefValid() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
const base::Value::Dict& background_info =
profile_->GetPrefs()->GetDict(prefs::kNtpCustomBackgroundDict);
pref_service_->GetDict(prefs::kNtpCustomBackgroundDict);

const base::Value* background_url =
background_info.Find(kNtpCustomBackgroundURL);
Expand Down
13 changes: 10 additions & 3 deletions chrome/browser/search/background/ntp_custom_background_service.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ class NtpCustomBackgroundService : public KeyedService,

// Invoked by Wallpaper Search to set background image with already decoded
// data.
virtual void SelectLocalBackgroundImage(const SkBitmap& bitmap);
virtual void SelectLocalBackgroundImage(const base::Token& id,
const SkBitmap& bitmap);

// Virtual for testing.
virtual void RefreshBackgroundIfNeeded();
Expand Down Expand Up @@ -118,7 +119,12 @@ class NtpCustomBackgroundService : public KeyedService,
virtual void VerifyCustomBackgroundImageURL();

private:
// Set bool pref for local background and clear id.
void SetBackgroundToLocalResource();

// Set bool pref for local background and set id.
void SetBackgroundToLocalResourceWithId(const base::Token& id);

void ForceRefreshBackground();
// Returns false if the custom background pref cannot be parsed, otherwise
// returns true.
Expand Down Expand Up @@ -146,8 +152,9 @@ class NtpCustomBackgroundService : public KeyedService,
int headers_response_code);

// Set background pref info to say that the current background is a local
// resource and start color extraction of the associated bitmap.
void SetBackgroundToLocalResourceAndExtractColor(const SkBitmap& bitmap);
// resource, set the id, and start color extraction of the associated bitmap.
void SetBackgroundToLocalResourceAndExtractColor(const base::Token& id,
const SkBitmap& bitmap);

const raw_ptr<Profile> profile_;
raw_ptr<PrefService, DanglingUntriaged> pref_service_;
Expand Down

0 comments on commit b95536f

Please sign in to comment.