blob: 82d63cf0543660a5e8ae30a825fd7e95195c2249 [file] [log] [blame]
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/search_box/search_box_view_base.h"
#include <algorithm>
#include <memory>
#include <vector>
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/app_list/app_list_color_provider.h"
#include "ash/search_box/search_box_view_delegate.h"
#include "base/bind.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/base/ime/text_input_flags.h"
#include "ui/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/border.h"
#include "ui/views/context_menu_controller.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace {
// The duration for the animation which changes the search icon.
constexpr base::TimeDelta kSearchIconAnimationDuration =
base::Milliseconds(250);
constexpr int kInnerPadding = 16;
constexpr int kFocusBorderThickness = 2;
// Preferred width of search box.
constexpr int kSearchBoxPreferredWidth = 544;
constexpr SkColor kSearchTextColor = SkColorSetRGB(0x33, 0x33, 0x33);
// The duration for the button fade out animation.
constexpr base::TimeDelta kButtonFadeOutDuration = base::Milliseconds(50);
// The delay for the button fade in animation.
constexpr base::TimeDelta kButtonFadeInDelay = base::Milliseconds(50);
// The duration for the button fade in animation.
constexpr base::TimeDelta kButtonFadeInDuration = base::Milliseconds(200);
} // namespace
// A background that paints a solid white rounded rect with a thin grey
// border.
class SearchBoxBackground : public views::Background {
public:
SearchBoxBackground(int corner_radius, SkColor color)
: corner_radius_(corner_radius) {
SetNativeControlColor(color);
}
SearchBoxBackground(const SearchBoxBackground&) = delete;
SearchBoxBackground& operator=(const SearchBoxBackground&) = delete;
~SearchBoxBackground() override = default;
void SetCornerRadius(int corner_radius) { corner_radius_ = corner_radius; }
private:
// views::Background overrides:
void Paint(gfx::Canvas* canvas, views::View* view) const override {
gfx::Rect bounds = view->GetContentsBounds();
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setColor(get_color());
canvas->DrawRoundRect(bounds, corner_radius_, flags);
}
int corner_radius_;
};
// To paint grey background on mic and back buttons, and close buttons for
// fullscreen launcher.
class SearchBoxImageButton : public views::ImageButton {
public:
explicit SearchBoxImageButton(PressedCallback callback)
: ImageButton(std::move(callback)) {
SetFocusBehavior(FocusBehavior::ALWAYS);
// Avoid drawing default dashed focus and draw customized focus in
// OnPaintBackground();
SetInstallFocusRingOnFocus(false);
// Inkdrop only on click.
views::InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::ON);
SetHasInkDropActionOnClick(true);
views::InkDrop::UseInkDropForFloodFillRipple(views::InkDrop::Get(this),
/*highlight_on_hover=*/false);
UpdateInkDropColors();
SetPaintToLayer();
layer()->SetFillsBoundsOpaquely(false);
SetPreferredSize(gfx::Size(kClassicSearchBoxButtonSizeDip,
kClassicSearchBoxButtonSizeDip));
SetImageHorizontalAlignment(ALIGN_CENTER);
SetImageVerticalAlignment(ALIGN_MIDDLE);
views::InstallCircleHighlightPathGenerator(this);
}
SearchBoxImageButton(const SearchBoxImageButton&) = delete;
SearchBoxImageButton& operator=(const SearchBoxImageButton&) = delete;
~SearchBoxImageButton() override {}
// views::View overrides:
bool OnKeyPressed(const ui::KeyEvent& event) override {
// Disable space key to press the button. The keyboard events received
// by this view are forwarded from a Textfield (SearchBoxView) and key
// released events are not forwarded. This leaves the button in pressed
// state.
if (event.key_code() == ui::VKEY_SPACE)
return false;
return Button::OnKeyPressed(event);
}
void OnFocus() override {
views::ImageButton::OnFocus();
SchedulePaint();
}
void OnBlur() override {
views::ImageButton::OnBlur();
SchedulePaint();
}
void OnThemeChanged() override {
views::View::OnThemeChanged();
UpdateInkDropColors();
}
void set_is_showing(bool is_showing) { is_showing_ = is_showing; }
bool is_showing() { return is_showing_; }
private:
int GetButtonRadius() const { return width() / 2; }
// Whether the button is showing/shown or hiding/hidden.
bool is_showing_ = false;
void UpdateInkDropColors() {
SkColor search_box_card_background_color =
AppListColorProvider::Get()->GetSearchBoxCardBackgroundColor();
views::InkDrop::Get(this)->SetBaseColor(
AppListColorProvider::Get()->GetInkDropBaseColor(
search_box_card_background_color));
views::InkDrop::Get(this)->SetVisibleOpacity(
AppListColorProvider::Get()->GetInkDropOpacity(
search_box_card_background_color));
}
// views::View overrides:
void OnPaintBackground(gfx::Canvas* canvas) override {
if (HasFocus()) {
cc::PaintFlags circle_flags;
circle_flags.setAntiAlias(true);
circle_flags.setColor(AppListColorProvider::Get()->GetFocusRingColor());
circle_flags.setStyle(cc::PaintFlags::kStroke_Style);
circle_flags.setStrokeWidth(kFocusBorderThickness);
canvas->DrawCircle(GetLocalBounds().CenterPoint(),
GetButtonRadius() - kFocusBorderThickness,
circle_flags);
}
}
const char* GetClassName() const override { return "SearchBoxImageButton"; }
};
// To show context menu of selected view instead of that of focused view which
// is always this view when the user uses keyboard shortcut to open context
// menu.
class SearchBoxTextfield : public views::Textfield {
public:
explicit SearchBoxTextfield(SearchBoxViewBase* search_box_view)
: search_box_view_(search_box_view) {}
SearchBoxTextfield(const SearchBoxTextfield&) = delete;
SearchBoxTextfield& operator=(const SearchBoxTextfield&) = delete;
~SearchBoxTextfield() override = default;
// Overridden from views::View:
void OnFocus() override {
search_box_view_->OnSearchBoxFocusedChanged();
Textfield::OnFocus();
}
void OnBlur() override {
search_box_view_->OnSearchBoxFocusedChanged();
// Clear selection and set the caret to the end of the text.
ClearSelection();
Textfield::OnBlur();
// Search box focus announcement overlaps with opening or closing folder
// alert, so we ignored the search box in those cases. Now reset the flag
// here.
auto& accessibility = GetViewAccessibility();
if (accessibility.IsIgnored()) {
accessibility.OverrideIsIgnored(false);
NotifyAccessibilityEvent(ax::mojom::Event::kTreeChanged, true);
}
}
void OnGestureEvent(ui::GestureEvent* event) override {
switch (event->type()) {
case ui::ET_GESTURE_LONG_PRESS:
case ui::ET_GESTURE_LONG_TAP:
// Prevent Long Press from being handled at all, if inactive
if (!search_box_view_->is_search_box_active()) {
event->SetHandled();
break;
}
// If |search_box_view_| is active, handle it as normal below
[[fallthrough]];
default:
// Handle all other events as normal
Textfield::OnGestureEvent(event);
}
}
void GetAccessibleNodeData(ui::AXNodeData* node_data) override {
views::Textfield::GetAccessibleNodeData(node_data);
search_box_view_->UpdateSearchTextfieldAccessibleNodeData(node_data);
}
private:
SearchBoxViewBase* const search_box_view_;
};
// Used to animate the transition between icon images. When a new icon is set,
// this view will temporarily store the layer of the previous icon and animate
// its opacity to fade out, while keeping the correct bounds for the fading out
// layer. At the same time the new icon will fade in.
class SearchIconImageView : public views::ImageView {
public:
SearchIconImageView() = default;
SearchIconImageView(const SearchIconImageView&) = delete;
SearchIconImageView& operator=(const SearchIconImageView&) = delete;
~SearchIconImageView() override = default;
// views::View:
void OnBoundsChanged(const gfx::Rect& previous_bounds) override {
if (old_icon_layer_)
old_icon_layer_->SetBounds(layer()->bounds());
views::ImageView::OnBoundsChanged(previous_bounds);
}
void SetSearchIconImage(gfx::ImageSkia image) {
if (GetImage().isNull() || !animation_enabled_) {
SetImage(image);
return;
}
if (old_icon_layer_ && old_icon_layer_->GetAnimator()->is_animating())
old_icon_layer_->GetAnimator()->StopAnimating();
old_icon_layer_ = RecreateLayer();
SetImage(image);
// Animate the old layer to fade out.
views::AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.OnEnded(base::BindOnce(&SearchIconImageView::ResetOldIconLayer,
weak_factory_.GetWeakPtr()))
.OnAborted(base::BindOnce(&SearchIconImageView::ResetOldIconLayer,
weak_factory_.GetWeakPtr()))
.Once()
.SetDuration(kSearchIconAnimationDuration)
.SetOpacity(old_icon_layer_.get(), 0.0f, gfx::Tween::EASE_OUT_3);
// Animate the newly set icon image to fade in.
layer()->SetOpacity(0.0f);
views::AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.Once()
.SetDuration(kSearchIconAnimationDuration)
.SetOpacity(layer(), 1.0f, gfx::Tween::EASE_OUT_3);
}
void ResetOldIconLayer() { old_icon_layer_.reset(); }
void set_animation_enabled(bool enabled) { animation_enabled_ = enabled; }
private:
std::unique_ptr<ui::Layer> old_icon_layer_;
bool animation_enabled_ = false;
base::WeakPtrFactory<SearchIconImageView> weak_factory_{this};
};
SearchBoxViewBase::SearchBoxViewBase(SearchBoxViewDelegate* delegate)
: delegate_(delegate),
content_container_(new views::View),
search_box_(new SearchBoxTextfield(this)) {
DCHECK(delegate_);
SetLayoutManager(std::make_unique<views::FillLayout>());
AddChildView(content_container_);
const int between_child_spacing =
kInnerPadding - views::LayoutProvider::Get()->GetDistanceMetric(
views::DISTANCE_TEXTFIELD_HORIZONTAL_TEXT_PADDING);
box_layout_ =
content_container_->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal,
gfx::Insets::VH(0, kSearchBoxPadding), between_child_spacing));
box_layout_->set_cross_axis_alignment(
views::BoxLayout::CrossAxisAlignment::kCenter);
box_layout_->set_minimum_cross_axis_size(kSearchBoxPreferredHeight);
search_box_->SetBorder(views::NullBorder());
search_box_->SetTextColor(kSearchTextColor);
search_box_->SetBackgroundColor(SK_ColorTRANSPARENT);
search_box_->set_controller(this);
search_box_->SetTextInputType(ui::TEXT_INPUT_TYPE_SEARCH);
search_box_->SetTextInputFlags(ui::TEXT_INPUT_FLAG_AUTOCORRECT_OFF);
search_box_->SetFontList(search_box_->GetFontList().DeriveWithSizeDelta(2));
search_box_->SetCursorEnabled(is_search_box_active_);
back_button_ =
content_container_->AddChildView(std::make_unique<SearchBoxImageButton>(
base::BindRepeating(&SearchBoxViewDelegate::BackButtonPressed,
base::Unretained(delegate_))));
search_icon_ =
content_container_->AddChildView(std::make_unique<SearchIconImageView>());
search_icon_->SetPaintToLayer();
search_icon_->layer()->SetFillsBoundsOpaquely(false);
content_container_->AddChildView(search_box_);
box_layout_->SetFlexForView(search_box_, 1);
// |search_box_button_container_| which will show either the assistant button,
// the close button, or nothing on the right side of the search box view.
search_box_button_container_ =
content_container_->AddChildView(std::make_unique<views::View>());
search_box_button_container_->SetLayoutManager(
std::make_unique<views::FillLayout>());
assistant_button_ = search_box_button_container_->AddChildView(
std::make_unique<SearchBoxImageButton>(
base::BindRepeating(&SearchBoxViewDelegate::AssistantButtonPressed,
base::Unretained(delegate_))));
assistant_button_->SetFlipCanvasOnPaintForRTLUI(false);
// Default hidden, child class should decide if it should shown.
assistant_button_->SetVisible(false);
close_button_ = search_box_button_container_->AddChildView(
std::make_unique<SearchBoxImageButton>(
base::BindRepeating(&SearchBoxViewDelegate::CloseButtonPressed,
base::Unretained(delegate_))));
}
SearchBoxViewBase::~SearchBoxViewBase() = default;
void SearchBoxViewBase::Init(const InitParams& params) {
show_close_button_when_active_ = params.show_close_button_when_active;
search_icon_->set_animation_enabled(params.animate_changing_search_icon);
SetPaintToLayer();
layer()->SetFillsBoundsOpaquely(false);
layer()->SetMasksToBounds(true);
if (params.create_background) {
SetBackground(std::make_unique<SearchBoxBackground>(
kSearchBoxBorderCornerRadius,
AppListColorProvider::Get()->GetSearchBoxBackgroundColor()));
}
if (params.increase_child_view_padding) {
box_layout_->set_between_child_spacing(kInnerPadding);
}
UpdateSearchBoxBorder();
UpdatePlaceholderTextStyle();
SetupAssistantButton();
SetupBackButton();
SetupCloseButton();
}
bool SearchBoxViewBase::HasSearch() const {
return !search_box_->GetText().empty();
}
gfx::Rect SearchBoxViewBase::GetViewBoundsForSearchBoxContentsBounds(
const gfx::Rect& rect) const {
gfx::Rect view_bounds = rect;
view_bounds.Inset(-GetInsets());
return view_bounds;
}
views::ImageButton* SearchBoxViewBase::assistant_button() {
return static_cast<views::ImageButton*>(assistant_button_);
}
views::ImageButton* SearchBoxViewBase::back_button() {
return static_cast<views::ImageButton*>(back_button_);
}
views::ImageButton* SearchBoxViewBase::close_button() {
return static_cast<views::ImageButton*>(close_button_);
}
views::ImageView* SearchBoxViewBase::search_icon() {
return search_icon_;
}
void SearchBoxViewBase::ShowBackOrGoogleIcon(bool show_back_button) {
search_icon_->SetVisible(!show_back_button);
back_button_->SetVisible(show_back_button);
content_container_->Layout();
}
void SearchBoxViewBase::SetSearchBoxActive(bool active,
ui::EventType event_type) {
if (active == is_search_box_active_)
return;
is_search_box_active_ = active;
UpdateSearchIcon();
UpdatePlaceholderTextStyle();
search_box_->SetCursorEnabled(active);
if (active) {
search_box_->RequestFocus();
RecordSearchBoxActivationHistogram(event_type);
} else {
search_box_->DestroyTouchSelection();
}
UpdateSearchBoxBorder();
// Keep the current keyboard visibility if the user already started typing.
if (event_type != ui::ET_KEY_PRESSED && event_type != ui::ET_KEY_RELEASED)
UpdateKeyboardVisibility();
UpdateButtonsVisibility();
OnSearchBoxActiveChanged(active);
NotifyActiveChanged();
content_container_->Layout();
UpdateSearchBoxFocusPaint();
SchedulePaint();
}
bool SearchBoxViewBase::OnTextfieldEvent(ui::EventType type) {
if (is_search_box_active_)
return false;
SetSearchBoxActive(true, type);
return true;
}
gfx::Size SearchBoxViewBase::CalculatePreferredSize() const {
return gfx::Size(kSearchBoxPreferredWidth, kSearchBoxPreferredHeight);
}
void SearchBoxViewBase::OnEnabledChanged() {
bool enabled = GetEnabled();
search_box_->SetEnabled(enabled);
if (close_button_)
close_button_->SetEnabled(enabled);
if (assistant_button_)
assistant_button_->SetEnabled(enabled);
}
const char* SearchBoxViewBase::GetClassName() const {
return "SearchBoxView";
}
void SearchBoxViewBase::OnKeyEvent(ui::KeyEvent* event) {
delegate_->OnSearchBoxKeyEvent(event);
}
void SearchBoxViewBase::OnGestureEvent(ui::GestureEvent* event) {
HandleSearchBoxEvent(event);
}
void SearchBoxViewBase::OnMouseEvent(ui::MouseEvent* event) {
HandleSearchBoxEvent(event);
}
void SearchBoxViewBase::NotifyGestureEvent() {
search_box_->DestroyTouchSelection();
}
void SearchBoxViewBase::OnSearchBoxFocusedChanged() {
UpdateSearchBoxBorder();
Layout();
UpdateSearchBoxFocusPaint();
SchedulePaint();
}
bool SearchBoxViewBase::IsSearchBoxTrimmedQueryEmpty() const {
std::u16string trimmed_query;
base::TrimWhitespace(search_box_->GetText(), base::TrimPositions::TRIM_ALL,
&trimmed_query);
return trimmed_query.empty();
}
void SearchBoxViewBase::UpdateSearchTextfieldAccessibleNodeData(
ui::AXNodeData* node_data) {}
void SearchBoxViewBase::ClearSearch() {
// Avoid setting |search_box_| text to empty if it is already empty.
if (search_box_->GetText() == std::u16string())
return;
search_box_->SetText(std::u16string());
UpdateButtonsVisibility();
// Updates model and fires query changed manually because SetText() above
// does not generate ContentsChanged() notification.
UpdateModel(false);
NotifyQueryChanged();
}
void SearchBoxViewBase::OnSearchBoxActiveChanged(bool active) {}
void SearchBoxViewBase::UpdateSearchBoxFocusPaint() {}
void SearchBoxViewBase::NotifyQueryChanged() {
DCHECK(delegate_);
delegate_->QueryChanged(this);
}
void SearchBoxViewBase::NotifyActiveChanged() {
DCHECK(delegate_);
delegate_->ActiveChanged(this);
}
void SearchBoxViewBase::UpdateButtonsVisibility() {
DCHECK(close_button_ && assistant_button_);
const bool should_show_close_button =
!search_box_->GetText().empty() ||
(show_close_button_when_active_ && is_search_box_active_);
const bool should_show_assistant_button =
show_assistant_button_ && !should_show_close_button;
if (should_show_close_button) {
MaybeFadeButtonIn(close_button_);
} else {
MaybeFadeButtonOut(close_button_);
}
if (should_show_assistant_button) {
MaybeFadeButtonIn(assistant_button_);
} else {
MaybeFadeButtonOut(assistant_button_);
}
}
void SearchBoxViewBase::MaybeFadeButtonIn(SearchBoxImageButton* button) {
if (button->GetVisible() && button->is_showing())
return;
if (!button->layer()->GetAnimator()->is_animating())
button->layer()->SetOpacity(0.0f);
views::AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.Once()
.At(kButtonFadeInDelay)
.SetDuration(kButtonFadeInDuration)
.SetOpacity(button->layer(), 1.0f, gfx::Tween::LINEAR);
// Set the button visible after scheduling the animation because scheduling
// the animation might abort a fade-out, which sets the button invisible.
button->SetVisible(true);
button->set_is_showing(true);
}
void SearchBoxViewBase::MaybeFadeButtonOut(SearchBoxImageButton* button) {
if (!button->GetVisible() || !button->is_showing())
return;
views::AnimationBuilder()
.SetPreemptionStrategy(
ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
.OnEnded(base::BindOnce(&SearchBoxViewBase::SetVisibilityHidden,
weak_factory_.GetWeakPtr(), button))
.OnAborted(base::BindOnce(&SearchBoxViewBase::SetVisibilityHidden,
weak_factory_.GetWeakPtr(), button))
.Once()
.SetDuration(kButtonFadeOutDuration)
.SetOpacity(button->layer(), 0.0f, gfx::Tween::LINEAR);
button->set_is_showing(false);
}
void SearchBoxViewBase::SetVisibilityHidden(SearchBoxImageButton* button) {
button->SetVisible(false);
}
void SearchBoxViewBase::ContentsChanged(views::Textfield* sender,
const std::u16string& new_contents) {
// Set search box focused when query changes.
search_box_->RequestFocus();
UpdateModel(true);
NotifyQueryChanged();
if (!new_contents.empty())
SetSearchBoxActive(true, ui::ET_KEY_PRESSED);
UpdateButtonsVisibility();
}
bool SearchBoxViewBase::HandleMouseEvent(views::Textfield* sender,
const ui::MouseEvent& mouse_event) {
return OnTextfieldEvent(mouse_event.type());
}
bool SearchBoxViewBase::HandleGestureEvent(
views::Textfield* sender,
const ui::GestureEvent& gesture_event) {
return OnTextfieldEvent(gesture_event.type());
}
void SearchBoxViewBase::SetSearchBoxBackgroundCornerRadius(int corner_radius) {
auto* search_box_background = static_cast<SearchBoxBackground*>(background());
if (search_box_background)
search_box_background->SetCornerRadius(corner_radius);
}
void SearchBoxViewBase::SetSearchIconImage(gfx::ImageSkia image) {
search_icon_->SetSearchIconImage(image);
}
void SearchBoxViewBase::SetShowAssistantButton(bool show) {
show_assistant_button_ = show;
UpdateButtonsVisibility();
}
void SearchBoxViewBase::HandleSearchBoxEvent(ui::LocatedEvent* located_event) {
if (located_event->type() == ui::ET_MOUSE_PRESSED ||
located_event->type() == ui::ET_GESTURE_TAP) {
const bool event_is_in_searchbox_bounds =
GetWidget()->GetWindowBoundsInScreen().Contains(
located_event->root_location());
// Don't handle an event out of the searchbox bounds.
if (!event_is_in_searchbox_bounds)
return;
// If the event is in an inactive empty search box, enable the search box.
if (!is_search_box_active_ && search_box_->GetText().empty()) {
SetSearchBoxActive(true, located_event->type());
return;
}
// Otherwise, update the keyboard in case it was hidden. Tapping again
// should reopen it.
UpdateKeyboardVisibility();
}
}
// TODO(crbug.com/755219): Unify this with SetBackgroundColor.
void SearchBoxViewBase::UpdateBackgroundColor(SkColor color) {
auto* search_box_background = background();
if (search_box_background)
search_box_background->SetNativeControlColor(color);
}
} // namespace ash