1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
|
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/profiles/avatar_toolbar_button.h"
#include <vector>
#include "base/auto_reset.h"
#include "base/check.h"
#include "base/compiler_specific.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/notreached.h"
#include "base/observer_list.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/app/vector_icons/vector_icons.h"
#include "chrome/browser/profiles/avatar_menu.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/sync_ui_util.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_element_identifiers.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/color/chrome_color_id.h"
#include "chrome/browser/ui/layout_constants.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/profiles/avatar_toolbar_button_delegate.h"
#include "chrome/browser/ui/views/profiles/profile_menu_coordinator.h"
#include "chrome/browser/ui/views/toolbar/toolbar_button.h"
#include "chrome/browser/ui/views/toolbar/toolbar_ink_drop_util.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "chrome/grit/branded_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/feature_engagement/public/feature_constants.h"
#include "components/feature_engagement/public/tracker.h"
#include "components/password_manager/content/common/web_ui_constants.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/tribool.h"
#include "components/user_education/common/user_education_class_properties.h"
#include "content/public/common/url_utils.h"
#include "google_apis/gaia/gaia_id.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/image_model_utils.h"
#include "ui/base/models/menu_model.h"
#include "ui/base/theme_provider.h"
#include "ui/base/ui_base_features.h"
#include "ui/color/color_provider.h"
#include "ui/compositor/layer.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/button_controller.h"
#include "ui/views/controls/button/label_button_border.h"
#include "ui/views/view_class_properties.h"
namespace {
constexpr int kChromeRefreshImageLabelPadding = 6;
// Value used to enlarge the AvatarIcon to accommodate for DIP scaling.
constexpr int kAvatarIconEnlargement = 1;
} // namespace
// static
base::TimeDelta AvatarToolbarButton::g_iph_min_delay_after_creation =
base::Seconds(2);
AvatarToolbarButton::AvatarToolbarButton(BrowserView* browser_view)
: ToolbarButton(base::BindRepeating(&AvatarToolbarButton::ButtonPressed,
base::Unretained(this),
/*is_source_accelerator=*/false)),
browser_(browser_view->browser()),
creation_time_(base::TimeTicks::Now()) {
CHECK(browser_);
delegate_ = std::make_unique<AvatarToolbarButtonDelegate>(this, browser_);
// Activate on press for left-mouse-button only to mimic other MenuButtons
// without drag-drop actions (specifically the adjacent browser menu).
button_controller()->set_notify_action(
views::ButtonController::NotifyAction::kOnPress);
SetTriggerableEventFlags(ui::EF_LEFT_MOUSE_BUTTON);
SetID(VIEW_ID_AVATAR_BUTTON);
SetProperty(views::kElementIdentifierKey, kToolbarAvatarButtonElementId);
// The avatar should not flip with RTL UI. This does not affect text rendering
// and LabelButton image/label placement is still flipped like usual.
SetFlipCanvasOnPaintForRTLUI(false);
GetViewAccessibility().SetHasPopup(ax::mojom::HasPopup::kMenu);
// For consistency with identity representation, we need to have the avatar on
// the left and the (potential) user name on the right.
SetHorizontalAlignment(gfx::ALIGN_LEFT);
SetImageLabelSpacing(kChromeRefreshImageLabelPadding);
label()->SetPaintToLayer();
label()->SetSkipSubpixelRenderingOpacityCheck(true);
label()->layer()->SetFillsBoundsOpaquely(false);
label()->SetSubpixelRenderingEnabled(false);
}
AvatarToolbarButton::~AvatarToolbarButton() = default;
void AvatarToolbarButton::UpdateIcon() {
// If the delegate state manager isn't initialized, that means the widget is
// not set yet and the button doesn't have access to the theme provider to set
// colors. Defer updating until AddedToWidget(). This may get called as a
// result of OnUserIdentityChanged() called from the constructor when the
// button is not yet added to the ToolbarView's hierarchy.
if (!delegate_->IsStateManagerInitialized()) {
return;
}
const int icon_size = GetIconSize();
const ui::ColorProvider* const color_provider = GetColorProvider();
CHECK(color_provider);
ui::ImageModel icon = delegate_->GetAvatarIcon(
icon_size, GetForegroundColor(ButtonState::STATE_NORMAL),
*color_provider);
SetImageModel(ButtonState::STATE_NORMAL, icon);
SetImageModel(ButtonState::STATE_DISABLED,
ui::GetDefaultDisabledIconFromImageModel(icon));
observer_list_.Notify(&Observer::OnIconUpdated);
}
void AvatarToolbarButton::AddedToWidget() {
// `AddedToWidget()` can potentially be called more than once. E.g: on Mac
// when entering/exiting fullscreen.
if (!delegate_->IsStateManagerInitialized()) {
delegate_->InitializeStateManager();
}
ToolbarButton::AddedToWidget();
// A call to `OnThemeChanged()` occurred before adding the widget, and could
// not be processed since the delegate was not initialized yet.
// This will also end up calling `UpdateIcon()`.
OnThemeChanged();
}
void AvatarToolbarButton::OnBoundsChanged(const gfx::Rect& previous_bounds) {
ToolbarButton::OnBoundsChanged(previous_bounds);
// This is needed to update the layout insets when the button is resized.
// `ToolbarButton::SetHighlight` may NOT clear the text immediately when the
// text is empty (clearing is delayed until the bounds are changed).
UpdateLayoutInsets();
}
void AvatarToolbarButton::Layout(PassKey) {
LayoutSuperclass<ToolbarButton>(this);
// TODO(crbug.com/40707582): this is a hack to avoid mismatch between avatar
// bitmap scaling and DIP->canvas pixel scaling in fractional DIP scaling
// modes (125%, 133%, etc.) that can cause the right-hand or bottom pixel row
// of the avatar image to be sliced off at certain specific browser sizes and
// configurations.
//
// In order to solve this, we increase the width and height of the image by 1
// after layout, so the rest of the layout is before. Since the profile image
// uses transparency, visually this does not cause any change in cases where
// the bug doesn't manifest.
auto* image = views::AsViewClass<views::ImageView>(image_container_view());
CHECK(image);
image->SetHorizontalAlignment(views::ImageView::Alignment::kLeading);
image->SetVerticalAlignment(views::ImageView::Alignment::kLeading);
gfx::Size image_size = image->GetImage().size();
image_size.Enlarge(kAvatarIconEnlargement, kAvatarIconEnlargement);
image->SetSize(image_size);
}
void AvatarToolbarButton::UpdateText() {
const auto* const color_provider = GetColorProvider();
CHECK(color_provider);
SetTooltipText(delegate_->GetAvatarTooltipText());
auto [text, color] = delegate_->GetTextAndColor(*color_provider);
SetHighlight(text, color);
UpdateAccessibilityLabel();
// Update the layout insets after `SetHighlight()` since
// text might be updated by setting the highlight.
UpdateLayoutInsets();
UpdateInkdrop();
// Outset focus ring should be present for the chip but not when only
// the icon is visible, when there is no text.
views::FocusRing::Get(this)->SetOutsetFocusRingDisabled(
!IsLabelPresentAndVisible());
// TODO(crbug.com/40689215): this is a hack because toolbar buttons don't
// correctly calculate their preferred size until they've been laid out once
// or twice, because they modify their own borders and insets in response to
// their size and have their own preferred size caching mechanic. These should
// both ideally be handled with a modern layout manager instead.
//
// In the meantime, to ensure that correct (or nearly correct) bounds are set,
// we will force a resize then invalidate layout to let the layout manager
// take over.
SizeToPreferredSize();
InvalidateLayout();
}
void AvatarToolbarButton::UpdateAccessibilityLabel() {
std::optional<std::u16string> accessibility_label =
delegate_->GetAccessibilityLabel();
std::u16string name;
std::u16string description;
// The button content text as well as the button action are modified
// dynamically with very different contexts. The accessibility label is not
// always present, but when it is, it is either used as the main text (through
// name) or as the secondary text (through description) if the button content
// exists. Adapt the description to match it's default when it is not the
// accessibility label: the tooltip or no text if the button content has no
// text initially. All the values needs to be overridden every time in order
// clear the previous state effect.
std::u16string button_content(GetText());
if (accessibility_label.has_value()) {
if (button_content.empty()) {
name = accessibility_label.value();
description = delegate_->GetAvatarTooltipText();
} else {
name = button_content;
description = accessibility_label.value();
}
} else {
if (button_content.empty()) {
name = delegate_->GetAvatarTooltipText();
description = std::u16string();
} else {
name = button_content;
description = delegate_->GetAvatarTooltipText();
}
}
GetViewAccessibility().SetName(name);
GetViewAccessibility().SetDescription(description);
}
std::optional<SkColor> AvatarToolbarButton::GetHighlightTextColor() const {
const auto* const color_provider = GetColorProvider();
CHECK(color_provider);
return delegate_->GetHighlightTextColor(*color_provider);
}
std::optional<SkColor> AvatarToolbarButton::GetHighlightBorderColor() const {
const auto* const color_provider = GetColorProvider();
CHECK(color_provider);
return color_provider->GetColor(kColorToolbarButtonBorder);
}
void AvatarToolbarButton::UpdateInkdrop() {
auto [hover_color_id, ripple_color_id] = delegate_->GetInkdropColors();
ConfigureToolbarInkdropForRefresh2023(this, hover_color_id, ripple_color_id);
}
bool AvatarToolbarButton::ShouldPaintBorder() const {
return IsLabelPresentAndVisible() && delegate_->ShouldPaintBorder();
}
bool AvatarToolbarButton::ShouldBlendHighlightColor() const {
if (base::FeatureList::IsEnabled(
features::kEnableAppMenuButtonColorsForDefaultAvatarButtonStates)) {
return false;
}
return GetWidget() && GetWidget()->GetCustomTheme();
}
base::ScopedClosureRunner AvatarToolbarButton::SetExplicitButtonState(
const std::u16string& text,
std::optional<std::u16string> accessibility_label,
std::optional<base::RepeatingCallback<void(bool)>> explicit_action) {
return delegate_->SetExplicitButtonState(text, std::move(accessibility_label),
std::move(explicit_action));
}
bool AvatarToolbarButton::HasExplicitButtonState() const {
return delegate_->HasExplicitButtonState();
}
void AvatarToolbarButton::SetButtonActionDisabled(bool disabled) {
button_action_disabled_ = disabled;
}
bool AvatarToolbarButton::IsButtonActionDisabled() const {
return button_action_disabled_;
}
void AvatarToolbarButton::MaybeShowProfileSwitchIPH() {
// Prevent showing the promo right when the browser was created. Wait a small
// delay for a smoother animation.
base::TimeDelta time_since_creation = base::TimeTicks::Now() - creation_time_;
if (time_since_creation < g_iph_min_delay_after_creation) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&AvatarToolbarButton::MaybeShowProfileSwitchIPH,
weak_ptr_factory_.GetWeakPtr()),
g_iph_min_delay_after_creation - time_since_creation);
return;
}
// This will show the promo only after the IPH system is properly initialized.
if (!web_app::AppBrowserController::IsWebApp(browser_)) {
browser_->window()->MaybeShowStartupFeaturePromo(
feature_engagement::kIPHProfileSwitchFeature);
} else {
// Installable PasswordManager WebUI is the only web app that has an avatar
// toolbar button.
auto app_url = browser_->app_controller()->GetAppStartUrl();
CHECK(content::HasWebUIScheme(app_url) &&
(app_url.host() == password_manager::kChromeUIPasswordManagerHost));
browser_->window()->MaybeShowStartupFeaturePromo(
feature_engagement::kIPHPasswordsWebAppProfileSwitchFeature);
}
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
void AvatarToolbarButton::MaybeShowSupervisedUserSignInIPH() {
if (!base::FeatureList::IsEnabled(
feature_engagement::kIPHSupervisedUserProfileSigninFeature)) {
return;
}
signin::IdentityManager* const identity_manager =
IdentityManagerFactory::GetForProfile(browser_->profile());
CHECK(identity_manager);
if (!identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSignin)) {
return;
}
auto account_info = identity_manager->FindExtendedAccountInfoByAccountId(
identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSignin));
if (account_info.capabilities.is_subject_to_parental_controls() !=
signin::Tribool::kTrue) {
return;
}
if (account_info.IsEmpty()) {
return;
}
// Prevent showing the promo right when the browser was created.
// This is not just used for smoother animation, but it gives the anchor
// element enough time to become visible and display the IPH.
// TODO(crbug.com/372689164): investigate alternative rescheduling,
// using `CanShowFeaturePromo`.
base::TimeDelta time_since_creation = base::TimeTicks::Now() - creation_time_;
if (time_since_creation < g_iph_min_delay_after_creation) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&AvatarToolbarButton::MaybeShowSupervisedUserSignInIPH,
weak_ptr_factory_.GetWeakPtr()),
g_iph_min_delay_after_creation - time_since_creation);
return;
}
user_education::FeaturePromoParams params(
feature_engagement::kIPHSupervisedUserProfileSigninFeature);
params.title_params = base::UTF8ToUTF16(account_info.given_name);
browser_->window()->MaybeShowFeaturePromo(std::move(params));
}
#endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
void AvatarToolbarButton::MaybeShowExplicitBrowserSigninPreferenceRememberedIPH(
const AccountInfo& account_info) {
user_education::FeaturePromoParams params(
feature_engagement::kIPHExplicitBrowserSigninPreferenceRememberedFeature,
account_info.gaia.ToString());
params.title_params = base::UTF8ToUTF16(account_info.given_name);
browser_->window()->MaybeShowFeaturePromo(std::move(params));
}
void AvatarToolbarButton::MaybeShowWebSignoutIPH(const GaiaId& gaia_id) {
browser_->window()->MaybeShowFeaturePromo(user_education::FeaturePromoParams(
feature_engagement::kIPHSignoutWebInterceptFeature, gaia_id.ToString()));
}
void AvatarToolbarButton::OnMouseExited(const ui::MouseEvent& event) {
observer_list_.Notify(&Observer::OnMouseExited);
ToolbarButton::OnMouseExited(event);
}
void AvatarToolbarButton::OnBlur() {
observer_list_.Notify(&Observer::OnBlur);
ToolbarButton::OnBlur();
}
void AvatarToolbarButton::OnThemeChanged() {
ToolbarButton::OnThemeChanged();
if (!delegate_->IsStateManagerInitialized()) {
return;
}
delegate_->OnThemeChanged(GetColorProvider());
UpdateText();
UpdateInkdrop();
}
// static
base::AutoReset<base::TimeDelta>
AvatarToolbarButton::SetScopedIPHMinDelayAfterCreationForTesting(
base::TimeDelta delay) {
return base::AutoReset<base::TimeDelta>(&g_iph_min_delay_after_creation,
delay);
}
void AvatarToolbarButton::ButtonPressed(bool is_source_accelerator) {
if (button_action_disabled_) {
return;
}
#if !BUILDFLAG(IS_CHROMEOS)
if (browser_->window()->IsFeaturePromoActive(
feature_engagement::kIPHPasswordsSavePrimingPromoFeature)) {
browser_->window()->NotifyFeaturePromoFeatureUsed(
feature_engagement::kIPHPasswordsSavePrimingPromoFeature,
FeaturePromoFeatureUsedAction::kClosePromoIfPresent);
}
#endif
delegate_->OnButtonPressed(is_source_accelerator);
}
void AvatarToolbarButton::AfterPropertyChange(const void* key,
int64_t old_value) {
if (key == user_education::kHasInProductHelpPromoKey) {
observer_list_.Notify(
&Observer::OnIPHPromoChanged,
GetProperty(user_education::kHasInProductHelpPromoKey));
}
ToolbarButton::AfterPropertyChange(key, old_value);
}
SkColor AvatarToolbarButton::GetForegroundColor(ButtonState state) const {
if (base::FeatureList::IsEnabled(
features::kEnableAppMenuButtonColorsForDefaultAvatarButtonStates)) {
if (IsLabelPresentAndVisible()) {
return GetHighlightTextColor().value_or(GetColorProvider()->GetColor(
kColorAvatarButtonHighlightDefaultForeground));
}
} else {
const bool has_custom_theme =
this->GetWidget() && this->GetWidget()->GetCustomTheme();
// If there is a custom theme use the `ToolbarButton` version of
// `GetForegroundColor()` This is to avoid creating new colorIds for icons
// for all the different states. With chrome refresh and without any custom
// theme, the color would be same as the label color.
if (!has_custom_theme && IsLabelPresentAndVisible()) {
const std::optional<SkColor> foreground_color = GetHighlightTextColor();
const auto* const color_provider = GetColorProvider();
return foreground_color.has_value()
? foreground_color.value()
: color_provider->GetColor(
kColorAvatarButtonHighlightDefaultForeground);
}
}
return ToolbarButton::GetForegroundColor(state);
}
bool AvatarToolbarButton::IsLabelPresentAndVisible() const {
if (!label()) {
return false;
}
return label()->GetVisible() && !label()->GetText().empty();
}
void AvatarToolbarButton::UpdateLayoutInsets() {
SetLayoutInsets(::GetLayoutInsets(
IsLabelPresentAndVisible() ? AVATAR_CHIP_PADDING : TOOLBAR_BUTTON));
}
int AvatarToolbarButton::GetIconSize() const {
return ui::TouchUiController::Get()->touch_ui()
? kDefaultTouchableIconSize
: kDefaultIconSizeChromeRefresh;
}
void AvatarToolbarButton::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void AvatarToolbarButton::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
// static
base::AutoReset<std::optional<base::TimeDelta>>
AvatarToolbarButton::CreateScopedInfiniteDelayOverrideForTesting(
AvatarDelayType delay_type) {
return AvatarToolbarButtonDelegate::
CreateScopedInfiniteDelayOverrideForTesting(delay_type);
}
void AvatarToolbarButton::TriggerTimeoutForTesting(AvatarDelayType delay_type) {
delegate_->TriggerTimeoutForTesting(delay_type); // IN-TEST
}
#if BUILDFLAG(ENABLE_DICE_SUPPORT)
// static
base::AutoReset<std::optional<base::TimeDelta>> AvatarToolbarButton::
CreateScopedZeroDelayOverrideSigninPendingTextForTesting() {
return AvatarToolbarButtonDelegate::
CreateScopedZeroDelayOverrideSigninPendingTextForTesting();
}
#endif // BUILDFLAG(ENABLE_DICE_SUPPORT)
BEGIN_METADATA(AvatarToolbarButton)
END_METADATA
|