#include "ui/views/widget/root_view.h"
#include <algorithm>
#include <memory>
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/raw_ref.h"
#include "base/scoped_observation.h"
#include "base/strings/string_piece.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/ui_base_switches_util.h"
#include "ui/compositor/layer.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/events/gestures/gesture_recognizer.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/canvas.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/drag_controller.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_targeter.h"
#include "ui/views/widget/root_view_targeter.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
using DispatchDetails = ui::EventDispatchDetails;
namespace views::internal {
namespace {
class MouseEnterExitEvent : public ui::MouseEvent {
public:
MouseEnterExitEvent(const ui::MouseEvent& event, ui::EventType type)
: ui::MouseEvent(event,
static_cast<View*>(nullptr),
static_cast<View*>(nullptr)) {
DCHECK(type == ui::ET_MOUSE_ENTERED || type == ui::ET_MOUSE_EXITED);
SetType(type);
}
~MouseEnterExitEvent() override = default;
std::unique_ptr<ui::Event> Clone() const override {
return std::make_unique<MouseEnterExitEvent>(*this);
}
};
}
class AnnounceTextView : public View {
public:
METADATA_HEADER(AnnounceTextView);
~AnnounceTextView() override = default;
void Announce(const std::u16string& text) {
announce_text_ = text;
NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true);
}
void GetAccessibleNodeData(ui::AXNodeData* node_data) override {
#if BUILDFLAG(IS_CHROMEOS)
node_data->role = ax::mojom::Role::kStaticText;
#else
node_data->role = ax::mojom::Role::kAlert;
#endif
node_data->SetNameChecked(announce_text_);
node_data->AddState(ax::mojom::State::kInvisible);
}
private:
std::u16string announce_text_;
};
BEGIN_METADATA(AnnounceTextView, View)
END_METADATA
class PreEventDispatchHandler : public ui::EventHandler {
public:
explicit PreEventDispatchHandler(View* owner) : owner_(owner) {
owner_->AddPreTargetHandler(this);
}
PreEventDispatchHandler(const PreEventDispatchHandler&) = delete;
PreEventDispatchHandler& operator=(const PreEventDispatchHandler&) = delete;
~PreEventDispatchHandler() override { owner_->RemovePreTargetHandler(this); }
private:
void OnKeyEvent(ui::KeyEvent* event) override {
CHECK_EQ(ui::EP_PRETARGET, event->phase());
#if !BUILDFLAG(IS_MAC)
if (event->handled())
return;
View* v = nullptr;
if (owner_->GetFocusManager())
v = owner_->GetFocusManager()->GetFocusedView();
if (v && v->GetEnabled() &&
((event->key_code() == ui::VKEY_APPS) ||
(event->key_code() == ui::VKEY_F10 && event->IsShiftDown()))) {
gfx::Point location = v->GetKeyboardContextMenuLocation();
for (View* parent = v->parent(); parent; parent = parent->parent()) {
const gfx::Rect& parent_bounds = parent->GetBoundsInScreen();
location.SetToMax(parent_bounds.origin());
location.SetToMin(parent_bounds.bottom_right());
}
v->ShowContextMenu(location, ui::MENU_SOURCE_KEYBOARD);
event->StopPropagation();
}
#endif
}
base::StringPiece GetLogContext() const override {
return "PreEventDispatchHandler";
}
raw_ptr<View> owner_;
};
class PostEventDispatchHandler : public ui::EventHandler {
public:
PostEventDispatchHandler()
: touch_dnd_enabled_(::switches::IsTouchDragDropEnabled()) {}
PostEventDispatchHandler(const PostEventDispatchHandler&) = delete;
PostEventDispatchHandler& operator=(const PostEventDispatchHandler&) = delete;
~PostEventDispatchHandler() override = default;
private:
void OnGestureEvent(ui::GestureEvent* event) override {
DCHECK_EQ(ui::EP_POSTTARGET, event->phase());
if (event->handled())
return;
View* target = static_cast<View*>(event->target());
gfx::Point location = event->location();
if (touch_dnd_enabled_ && event->type() == ui::ET_GESTURE_LONG_PRESS &&
(!target->drag_controller() ||
target->drag_controller()->CanStartDragForView(target, location,
location))) {
if (target->DoDrag(*event, location,
ui::mojom::DragEventSource::kTouch)) {
event->StopPropagation();
return;
}
}
if (target->context_menu_controller() &&
(event->type() == ui::ET_GESTURE_LONG_PRESS ||
event->type() == ui::ET_GESTURE_LONG_TAP ||
event->type() == ui::ET_GESTURE_TWO_FINGER_TAP)) {
gfx::Point screen_location(location);
View::ConvertPointToScreen(target, &screen_location);
target->ShowContextMenu(screen_location, ui::MENU_SOURCE_TOUCH);
event->StopPropagation();
}
}
base::StringPiece GetLogContext() const override {
return "PostEventDispatchHandler";
}
bool touch_dnd_enabled_;
};
RootView::RootView(Widget* widget)
: widget_(widget),
pre_dispatch_handler_(
std::make_unique<internal::PreEventDispatchHandler>(this)),
post_dispatch_handler_(
std::make_unique<internal::PostEventDispatchHandler>()) {
AddPostTargetHandler(post_dispatch_handler_.get());
SetEventTargeter(
std::unique_ptr<ViewTargeter>(new RootViewTargeter(this, this)));
}
RootView::~RootView() {
RemoveAllChildViews();
}
void RootView::SetContentsView(View* contents_view) {
DCHECK(contents_view && GetWidget()->native_widget())
<< "Can't be called because the widget is not initialized or is "
"destroyed";
SetUseDefaultFillLayout(true);
if (!children().empty())
RemoveAllChildViews();
AddChildView(contents_view);
}
View* RootView::GetContentsView() {
return children().empty() ? nullptr : children().front();
}
void RootView::NotifyNativeViewHierarchyChanged() {
PropagateNativeViewHierarchyChanged();
}
void RootView::SetFocusTraversableParent(FocusTraversable* focus_traversable) {
DCHECK(focus_traversable != this);
focus_traversable_parent_ = focus_traversable;
}
void RootView::SetFocusTraversableParentView(View* view) {
focus_traversable_parent_view_ = view;
}
void RootView::ThemeChanged() {
View::PropagateThemeChanged();
}
void RootView::ResetEventHandlers() {
explicit_mouse_handler_ = false;
mouse_pressed_handler_ = nullptr;
mouse_move_handler_ = nullptr;
gesture_handler_ = nullptr;
event_dispatch_target_ = nullptr;
old_dispatch_target_ = nullptr;
}
void RootView::DeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {
View::PropagateDeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
}
AnnounceTextView* RootView::GetOrCreateAnnounceView() {
if (!announce_view_) {
announce_view_ = AddChildView(std::make_unique<AnnounceTextView>());
announce_view_->SetProperty(kViewIgnoredByLayoutKey, true);
}
return announce_view_.get();
}
void RootView::AnnounceText(const std::u16string& text) {
#if BUILDFLAG(IS_MAC)
gfx::NativeViewAccessible native = GetViewAccessibility().GetNativeObject();
auto* ax_node = ui::AXPlatformNode::FromNativeViewAccessible(native);
if (ax_node)
ax_node->AnnounceText(text);
#else
DCHECK(GetWidget());
DCHECK(GetContentsView());
GetOrCreateAnnounceView()->Announce(text);
#endif
}
View* RootView::GetAnnounceViewForTesting() {
return GetOrCreateAnnounceView();
}
FocusSearch* RootView::GetFocusSearch() {
return &focus_search_;
}
FocusTraversable* RootView::GetFocusTraversableParent() {
return focus_traversable_parent_;
}
View* RootView::GetFocusTraversableParentView() {
return focus_traversable_parent_view_;
}
ui::EventTarget* RootView::GetRootForEvent(ui::Event* event) {
return this;
}
ui::EventTargeter* RootView::GetDefaultEventTargeter() {
return this->GetEventTargeter();
}
void RootView::OnEventProcessingStarted(ui::Event* event) {
VLOG(5) << "RootView::OnEventProcessingStarted(" << event->ToString() << ")";
if (!event->IsGestureEvent())
return;
ui::GestureEvent* gesture_event = event->AsGestureEvent();
if (gesture_event->type() == ui::ET_GESTURE_BEGIN) {
event->SetHandled();
return;
}
if (gesture_event->type() == ui::ET_GESTURE_END &&
(gesture_event->details().touch_points() > 1 || !gesture_handler_)) {
event->SetHandled();
return;
}
if (!gesture_handler_ &&
(gesture_event->type() == ui::ET_GESTURE_SCROLL_UPDATE ||
gesture_event->type() == ui::ET_GESTURE_SCROLL_END ||
gesture_event->type() == ui::ET_SCROLL_FLING_START)) {
event->SetHandled();
return;
}
gesture_handler_set_before_processing_ = !!gesture_handler_;
}
void RootView::OnEventProcessingFinished(ui::Event* event) {
VLOG(5) << "RootView::OnEventProcessingFinished(" << event->ToString() << ")";
if (event->IsGestureEvent() && !event->handled() &&
!gesture_handler_set_before_processing_) {
gesture_handler_ = nullptr;
}
}
const Widget* RootView::GetWidget() const {
return widget_;
}
Widget* RootView::GetWidget() {
return const_cast<Widget*>(const_cast<const RootView*>(this)->GetWidget());
}
bool RootView::IsDrawn() const {
return GetVisible();
}
bool RootView::OnMousePressed(const ui::MouseEvent& event) {
UpdateCursor(event);
SetMouseLocationAndFlags(event);
if (mouse_pressed_handler_) {
ui::MouseEvent mouse_pressed_event(event, static_cast<View*>(this),
mouse_pressed_handler_.get());
drag_info_.Reset();
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_pressed_handler_, &mouse_pressed_event);
if (dispatch_details.dispatcher_destroyed)
return true;
return true;
}
DCHECK(!explicit_mouse_handler_);
for (mouse_pressed_handler_ = GetEventHandlerForPoint(event.location());
mouse_pressed_handler_ && (mouse_pressed_handler_ != this);
mouse_pressed_handler_ = mouse_pressed_handler_->parent()) {
DVLOG(1) << "OnMousePressed testing "
<< mouse_pressed_handler_->GetClassName();
DCHECK(mouse_pressed_handler_->GetEnabled());
ui::MouseEvent mouse_pressed_event(event, static_cast<View*>(this),
mouse_pressed_handler_.get());
if (mouse_pressed_handler_ != last_click_handler_)
mouse_pressed_event.set_flags(event.flags() & ~ui::EF_IS_DOUBLE_CLICK);
drag_info_.Reset();
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_pressed_handler_, &mouse_pressed_event);
if (dispatch_details.dispatcher_destroyed)
return mouse_pressed_event.handled();
if (!mouse_pressed_handler_)
break;
if (mouse_pressed_event.handled()) {
last_click_handler_ = mouse_pressed_handler_;
DVLOG(1) << "OnMousePressed handled by "
<< mouse_pressed_handler_->GetClassName();
return true;
}
}
mouse_pressed_handler_ = nullptr;
const bool last_click_was_handled = (last_click_handler_ != nullptr);
last_click_handler_ = nullptr;
return last_click_was_handled && (event.flags() & ui::EF_IS_DOUBLE_CLICK);
}
bool RootView::OnMouseDragged(const ui::MouseEvent& event) {
if (mouse_pressed_handler_) {
SetMouseLocationAndFlags(event);
ui::MouseEvent mouse_event(event, static_cast<View*>(this),
mouse_pressed_handler_.get());
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_pressed_handler_, &mouse_event);
if (dispatch_details.dispatcher_destroyed)
return false;
return true;
}
return false;
}
void RootView::OnMouseReleased(const ui::MouseEvent& event) {
UpdateCursor(event);
if (mouse_pressed_handler_) {
ui::MouseEvent mouse_released(event, static_cast<View*>(this),
mouse_pressed_handler_.get());
View* mouse_pressed_handler = mouse_pressed_handler_;
SetMouseAndGestureHandler(nullptr);
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_pressed_handler, &mouse_released);
if (dispatch_details.dispatcher_destroyed)
return;
}
}
void RootView::OnMouseCaptureLost() {
if (mouse_pressed_handler_ || gesture_handler_) {
if (mouse_pressed_handler_) {
gfx::Point last_point(last_mouse_event_x_, last_mouse_event_y_);
ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, last_point,
last_point, ui::EventTimeForNow(),
last_mouse_event_flags_, 0);
UpdateCursor(release_event);
}
View* mouse_pressed_handler = mouse_pressed_handler_;
View* gesture_handler = gesture_handler_;
SetMouseAndGestureHandler(nullptr);
if (mouse_pressed_handler)
mouse_pressed_handler->OnMouseCaptureLost();
else
gesture_handler->OnMouseCaptureLost();
}
}
void RootView::OnMouseMoved(const ui::MouseEvent& event) {
View* v = GetEventHandlerForPoint(event.location());
if (mouse_move_handler_ && !mouse_move_handler_->GetEnabled() &&
v->Contains(mouse_move_handler_))
v = mouse_move_handler_;
if (v && v != this) {
if (v != mouse_move_handler_) {
if (mouse_move_handler_ != nullptr &&
(!mouse_move_handler_->GetNotifyEnterExitOnChild() ||
!mouse_move_handler_->Contains(v))) {
MouseEnterExitEvent exit(event, ui::ET_MOUSE_EXITED);
exit.ConvertLocationToTarget(static_cast<View*>(this),
mouse_move_handler_.get());
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_move_handler_, &exit);
if (dispatch_details.dispatcher_destroyed)
return;
if (!dispatch_details.target_destroyed) {
if (!mouse_move_handler_)
return;
dispatch_details = NotifyEnterExitOfDescendant(
event, ui::ET_MOUSE_EXITED, mouse_move_handler_, v);
if (dispatch_details.dispatcher_destroyed)
return;
}
}
View* old_handler = mouse_move_handler_;
mouse_move_handler_ = v;
if (!mouse_move_handler_->GetNotifyEnterExitOnChild() ||
!mouse_move_handler_->Contains(old_handler)) {
MouseEnterExitEvent entered(event, ui::ET_MOUSE_ENTERED);
entered.ConvertLocationToTarget(static_cast<View*>(this),
mouse_move_handler_.get());
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_move_handler_, &entered);
if (dispatch_details.dispatcher_destroyed ||
dispatch_details.target_destroyed) {
return;
}
if (!mouse_move_handler_)
return;
dispatch_details = NotifyEnterExitOfDescendant(
event, ui::ET_MOUSE_ENTERED, mouse_move_handler_, old_handler);
if (dispatch_details.dispatcher_destroyed ||
dispatch_details.target_destroyed) {
return;
}
}
}
ui::MouseEvent moved_event(event, static_cast<View*>(this),
mouse_move_handler_.get());
mouse_move_handler_->OnMouseMoved(moved_event);
if (!(moved_event.flags() & ui::EF_IS_NON_CLIENT))
widget_->SetCursor(mouse_move_handler_->GetCursor(moved_event));
} else if (mouse_move_handler_ != nullptr) {
MouseEnterExitEvent exited(event, ui::ET_MOUSE_EXITED);
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_move_handler_, &exited);
if (dispatch_details.dispatcher_destroyed)
return;
if (!dispatch_details.target_destroyed) {
if (!mouse_move_handler_)
return;
dispatch_details = NotifyEnterExitOfDescendant(event, ui::ET_MOUSE_EXITED,
mouse_move_handler_, v);
if (dispatch_details.dispatcher_destroyed)
return;
}
if (!(event.flags() & ui::EF_IS_NON_CLIENT))
widget_->SetCursor(ui::Cursor());
mouse_move_handler_ = nullptr;
}
}
void RootView::OnMouseExited(const ui::MouseEvent& event) {
if (mouse_move_handler_ != nullptr) {
MouseEnterExitEvent exited(event, ui::ET_MOUSE_EXITED);
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_move_handler_, &exited);
if (dispatch_details.dispatcher_destroyed)
return;
if (!dispatch_details.target_destroyed) {
CHECK(mouse_move_handler_);
dispatch_details = NotifyEnterExitOfDescendant(
event, ui::ET_MOUSE_EXITED, mouse_move_handler_, nullptr);
if (dispatch_details.dispatcher_destroyed)
return;
}
mouse_move_handler_ = nullptr;
}
}
bool RootView::OnMouseWheel(const ui::MouseWheelEvent& event) {
for (View* v = GetEventHandlerForPoint(event.location());
v && v != this && !event.handled(); v = v->parent()) {
ui::EventDispatchDetails dispatch_details =
DispatchEvent(v, const_cast<ui::MouseWheelEvent*>(&event));
if (dispatch_details.dispatcher_destroyed ||
dispatch_details.target_destroyed) {
return event.handled();
}
}
return event.handled();
}
void RootView::MaybeNotifyGestureHandlerBeforeReplacement() {
#if defined(USE_AURA)
ui::GestureRecognizer* gesture_recognizer =
(gesture_handler_ && widget_ ? widget_->GetGestureRecognizer() : nullptr);
if (!gesture_recognizer)
return;
ui::GestureConsumer* gesture_consumer = widget_->GetGestureConsumer();
if (!gesture_recognizer->DoesConsumerHaveActiveTouch(gesture_consumer))
return;
gesture_recognizer->SendSynthesizedEndEvents(gesture_consumer);
#endif
}
void RootView::SetMouseAndGestureHandler(View* new_handler) {
SetMouseHandler(new_handler);
if (new_handler == gesture_handler_)
return;
MaybeNotifyGestureHandlerBeforeReplacement();
gesture_handler_ = new_handler;
}
void RootView::SetMouseHandler(View* new_mouse_handler) {
explicit_mouse_handler_ = (new_mouse_handler != nullptr);
mouse_pressed_handler_ = new_mouse_handler;
drag_info_.Reset();
}
void RootView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
View::GetAccessibleNodeData(node_data);
DCHECK(GetWidget());
auto* widget_delegate = GetWidget()->widget_delegate();
if (!widget_delegate) {
return;
}
if (node_data->role == ax::mojom::Role::kUnknown) {
node_data->role = widget_delegate->GetAccessibleWindowRole();
}
if (node_data->GetStringAttribute(ax::mojom::StringAttribute::kName)
.empty() &&
static_cast<ax::mojom::NameFrom>(
node_data->GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)) !=
ax::mojom::NameFrom::kAttributeExplicitlyEmpty) {
node_data->SetName(widget_delegate->GetAccessibleWindowTitle());
}
}
void RootView::UpdateParentLayer() {
if (layer())
ReparentLayer(widget_->GetLayer());
}
void RootView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
widget_->ViewHierarchyChanged(details);
if (!details.is_add && !details.move_view) {
if (mouse_pressed_handler_ == details.child) {
SetMouseHandler(nullptr);
}
if (mouse_move_handler_ == details.child) {
mouse_move_handler_ = nullptr;
}
if (gesture_handler_ == details.child) {
gesture_handler_ = nullptr;
}
if (event_dispatch_target_ == details.child) {
event_dispatch_target_ = nullptr;
}
if (old_dispatch_target_ == details.child) {
old_dispatch_target_ = nullptr;
}
}
}
void RootView::VisibilityChanged(View* , bool is_visible) {
if (!is_visible) {
ResetEventHandlers();
}
}
void RootView::OnDidSchedulePaint(const gfx::Rect& rect) {
if (!layer()) {
gfx::Rect xrect = ConvertRectToParent(rect);
gfx::Rect invalid_rect = gfx::IntersectRects(GetLocalBounds(), xrect);
if (!invalid_rect.IsEmpty())
widget_->SchedulePaintInRect(invalid_rect);
}
}
void RootView::OnPaint(gfx::Canvas* canvas) {
if (!layer() || !layer()->fills_bounds_opaquely())
canvas->DrawColor(SK_ColorTRANSPARENT, SkBlendMode::kClear);
View::OnPaint(canvas);
}
View::LayerOffsetData RootView::CalculateOffsetToAncestorWithLayer(
ui::Layer** layer_parent) {
if (layer() || !widget_->GetLayer())
return View::CalculateOffsetToAncestorWithLayer(layer_parent);
if (layer_parent)
*layer_parent = widget_->GetLayer();
return LayerOffsetData(widget_->GetLayer()->device_scale_factor());
}
View::DragInfo* RootView::GetDragInfo() {
return &drag_info_;
}
void RootView::UpdateCursor(const ui::MouseEvent& event) {
if (!(event.flags() & ui::EF_IS_NON_CLIENT)) {
View* v = GetEventHandlerForPoint(event.location());
ui::MouseEvent me(event, static_cast<View*>(this), v);
widget_->SetCursor(v->GetCursor(me));
}
}
void RootView::SetMouseLocationAndFlags(const ui::MouseEvent& event) {
last_mouse_event_flags_ = event.flags();
last_mouse_event_x_ = event.x();
last_mouse_event_y_ = event.y();
}
ui::EventDispatchDetails RootView::NotifyEnterExitOfDescendant(
const ui::MouseEvent& event,
ui::EventType type,
View* view,
View* sibling) {
for (View* p = view->parent(); p; p = p->parent()) {
if (!p->GetNotifyEnterExitOnChild())
continue;
if (sibling && p->Contains(sibling))
break;
MouseEnterExitEvent notify_event(event, type);
ui::EventDispatchDetails dispatch_details = DispatchEvent(p, ¬ify_event);
if (dispatch_details.dispatcher_destroyed ||
dispatch_details.target_destroyed) {
return dispatch_details;
}
}
return ui::EventDispatchDetails();
}
bool RootView::CanDispatchToTarget(ui::EventTarget* target) {
return event_dispatch_target_ == target;
}
ui::EventDispatchDetails RootView::PreDispatchEvent(ui::EventTarget* target,
ui::Event* event) {
View* view = static_cast<View*>(target);
if (event->IsGestureEvent()) {
gesture_handler_ = view;
}
old_dispatch_target_ = event_dispatch_target_;
event_dispatch_target_ = view;
return DispatchDetails();
}
ui::EventDispatchDetails RootView::PostDispatchEvent(ui::EventTarget* target,
const ui::Event& event) {
if (event.type() == ui::ET_GESTURE_END) {
if (gesture_handler_ && gesture_handler_ == mouse_pressed_handler_)
SetMouseAndGestureHandler(nullptr);
else
gesture_handler_ = nullptr;
}
DispatchDetails details;
if (target != event_dispatch_target_)
details.target_destroyed = true;
event_dispatch_target_ = old_dispatch_target_;
old_dispatch_target_ = nullptr;
#ifndef NDEBUG
DCHECK(!event_dispatch_target_ || Contains(event_dispatch_target_));
#endif
return details;
}
BEGIN_METADATA(RootView, View)
END_METADATA
}