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 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
|
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/interaction/element_tracker.h"
#include <algorithm>
#include <iterator>
#include <list>
#include <map>
#include <sstream>
#include "base/callback_list.h"
#include "base/containers/contains.h"
#include "base/dcheck_is_on.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "ui/base/interaction/element_identifier.h"
namespace ui {
DEFINE_CLASS_ELEMENT_IDENTIFIER_VALUE(ElementTracker, kTemporaryIdentifier);
class ElementTracker::ElementData {
public:
ElementData(ElementTracker* tracker,
ElementIdentifier id,
ElementContext context)
: identifier_(id), context_(context) {
auto removal_callback =
base::BindRepeating(&ElementTracker::MaybeCleanup,
base::Unretained(tracker), base::Unretained(this));
shown_callbacks_.set_removal_callback(removal_callback);
activated_callbacks_.set_removal_callback(removal_callback);
hidden_callbacks_.set_removal_callback(removal_callback);
custom_event_callbacks_.set_removal_callback(removal_callback);
}
~ElementData() = default;
ElementIdentifier identifier() const { return identifier_; }
ElementContext context() const { return context_; }
bool HasElement(const TrackedElement* element) const {
return base::Contains(element_lookup_, element);
}
bool empty() const {
return elements_.empty() && shown_callbacks_.empty() &&
activated_callbacks_.empty() && hidden_callbacks_.empty() &&
custom_event_callbacks_.empty();
}
size_t num_elements() const {
// Guaranteed O(1) in C++11 and later.
return elements_.size();
}
const std::list<raw_ptr<TrackedElement, CtnExperimental>>& elements() const {
return elements_;
}
Subscription AddElementShownCallback(Callback callback) {
return shown_callbacks_.Add(callback);
}
Subscription AddElementActivatedCallback(Callback callback) {
return activated_callbacks_.Add(callback);
}
Subscription AddElementHiddenCallback(Callback callback) {
return hidden_callbacks_.Add(callback);
}
Subscription AddCustomEventCallback(Callback callback) {
return custom_event_callbacks_.Add(callback);
}
void NotifyElementShown(raw_ptr<TrackedElement, CtnExperimental>& element) {
DCHECK(element);
DCHECK_EQ(identifier(), element->identifier());
// Zero context data is the "all contexts" entry and doesn't actually store
// new elements, just calls callbacks.
if (context()) {
DCHECK_EQ(static_cast<intptr_t>(context()),
static_cast<intptr_t>(element->context()));
const auto it = elements_.insert(elements_.end(), element);
const bool success = element_lookup_.emplace(element, it).second;
DCHECK(success);
}
shown_callbacks_.Notify(element);
}
void NotifyElementActivated(
raw_ptr<TrackedElement, CtnExperimental>& element) {
// Note: "All contexts" does not require the element to be present here.
DCHECK(!context_ || base::Contains(element_lookup_, element));
activated_callbacks_.Notify(element);
}
void NotifyElementHidden(TrackedElement* element) {
if (context_) {
const auto it = element_lookup_.find(element);
CHECK(it != element_lookup_.end());
elements_.erase(it->second);
element_lookup_.erase(it);
}
hidden_callbacks_.Notify(element);
}
void NotifyCustomEvent(TrackedElement* element) {
custom_event_callbacks_.Notify(element);
}
private:
const ElementIdentifier identifier_;
const ElementContext context_;
// Holds elements in the order they were added to this data block, so that the
// first element or the first element that matches some criterion can be
// easily found.
std::list<raw_ptr<TrackedElement, CtnExperimental>> elements_;
// Provides a fast lookup into `elements_` by element for checking and
// removal. Since there could be many elements (e.g. tabs in a browser) we
// don't want removing a series of them to turn into an O(n^2) operation.
std::map<const TrackedElement*,
std::list<raw_ptr<TrackedElement, CtnExperimental>>::iterator>
element_lookup_;
base::RepeatingCallbackList<void(TrackedElement*)> shown_callbacks_;
base::RepeatingCallbackList<void(TrackedElement*)> activated_callbacks_;
base::RepeatingCallbackList<void(TrackedElement*)> hidden_callbacks_;
base::RepeatingCallbackList<void(TrackedElement*)> custom_event_callbacks_;
};
// Ensures that ElementData objects get cleaned up, but only after all callbacks
// have returned. Otherwise a subscription could be canceled during a callback,
// resulting in the ElementData and the callback list being deleted before the
// callback has returned.
class ElementTracker::GarbageCollector {
public:
// Represents a call stack frame in which garbage collection can happen.
// Garbage collection doesn't actually occur until all nested Frames are
// destructed.
class Frame {
public:
explicit Frame(GarbageCollector* gc) : gc_(gc) {
gc_->IncrementFrameCount();
}
~Frame() { gc_->DecrementFrameCount(); }
void Add(ElementData* data) { gc_->AddCandidate(data); }
private:
const raw_ptr<GarbageCollector> gc_;
};
explicit GarbageCollector(ElementTracker* tracker) : tracker_(tracker) {}
private:
void AddCandidate(ElementData* data) {
DCHECK_GE(frame_count_, 0);
candidates_.insert(data);
}
void IncrementFrameCount() { ++frame_count_; }
void DecrementFrameCount() {
DCHECK_GE(frame_count_, 0);
if (--frame_count_ > 0)
return;
for (ElementData* data : candidates_) {
if (data->empty()) {
const auto result = tracker_->element_data_.erase(
LookupKey(data->identifier(), data->context()));
DCHECK(result);
}
}
candidates_.clear();
}
const raw_ptr<ElementTracker> tracker_;
std::set<raw_ptr<ElementData, SetExperimental>> candidates_;
int frame_count_ = 0;
};
TrackedElement::TrackedElement(ElementIdentifier id, ElementContext context)
: identifier_(id), context_(context) {}
TrackedElement::~TrackedElement() = default;
gfx::Rect TrackedElement::GetScreenBounds() const {
return gfx::Rect();
}
std::string TrackedElement::ToString() const {
std::ostringstream oss;
oss << GetImplementationName() << "(" << identifier() << ", " << context()
<< ")";
return oss.str();
}
// static
ElementTracker* ElementTracker::GetElementTracker() {
static base::NoDestructor<ElementTracker> instance;
return instance.get();
}
// static
ElementTrackerFrameworkDelegate* ElementTracker::GetFrameworkDelegate() {
return static_cast<ElementTrackerFrameworkDelegate*>(GetElementTracker());
}
TrackedElement* ElementTracker::GetUniqueElement(ElementIdentifier id,
ElementContext context) {
const auto it = element_data_.find(LookupKey(id, context));
if (it == element_data_.end() || it->second.num_elements() == 0)
return nullptr;
DCHECK_EQ(1U, it->second.num_elements());
return it->second.elements().front();
}
TrackedElement* ElementTracker::GetFirstMatchingElement(
ElementIdentifier id,
ElementContext context) {
const auto it = element_data_.find(LookupKey(id, context));
if (it == element_data_.end() || it->second.num_elements() == 0)
return nullptr;
return it->second.elements().front();
}
TrackedElement* ElementTracker::GetElementInAnyContext(ElementIdentifier id) {
for (const auto& [key, data] : element_data_) {
if (key.first == id && !data.elements().empty())
return data.elements().front();
}
return nullptr;
}
ElementTracker::ElementList ElementTracker::GetAllMatchingElements(
ElementIdentifier id,
ElementContext context) {
const auto it = element_data_.find(LookupKey(id, context));
ElementList result;
if (it != element_data_.end()) {
std::ranges::copy(it->second.elements(), std::back_inserter(result));
}
return result;
}
ElementTracker::ElementList ElementTracker::GetAllMatchingElementsInAnyContext(
ElementIdentifier id) {
ElementList result;
for (const auto& [key, data] : element_data_) {
if (key.first == id) {
std::ranges::copy(data.elements(), std::back_inserter(result));
}
}
return result;
}
bool ElementTracker::IsElementVisible(ElementIdentifier id,
ElementContext context) {
const auto it = element_data_.find(LookupKey(id, context));
return it != element_data_.end() && it->second.num_elements() > 0;
}
ElementTracker::Contexts ElementTracker::GetAllContextsForTesting() const {
Contexts result;
for (const auto& [key, data] : element_data_) {
result.insert(key.second);
}
return result;
}
ElementTracker::ElementList ElementTracker::GetAllElementsForTesting(
std::optional<ElementContext> in_context) {
ElementList result;
for (const auto& [key, data] : element_data_) {
if (!in_context.has_value() || in_context.value() == key.second) {
std::copy(data.elements().begin(), data.elements().end(),
std::back_inserter(result));
}
}
return result;
}
ElementTracker::Subscription
ElementTracker::AddAnyElementShownCallbackForTesting(Callback callback) {
return any_element_shown_callbacks_.Add(std::move(callback));
}
ElementTracker::Subscription ElementTracker::AddElementShownCallback(
ElementIdentifier id,
ElementContext context,
Callback callback) {
DCHECK(id);
DCHECK(context);
return GetOrAddElementData(id, context)->AddElementShownCallback(callback);
}
ElementTracker::Subscription
ElementTracker::AddElementShownInAnyContextCallback(ElementIdentifier id,
Callback callback) {
DCHECK(id);
return GetOrAddElementData(id, ElementContext())
->AddElementShownCallback(callback);
}
ElementTracker::Subscription ElementTracker::AddElementActivatedCallback(
ElementIdentifier id,
ElementContext context,
Callback callback) {
DCHECK(id);
DCHECK(context);
return GetOrAddElementData(id, context)
->AddElementActivatedCallback(callback);
}
ElementTracker::Subscription
ElementTracker::AddElementActivatedInAnyContextCallback(ElementIdentifier id,
Callback callback) {
DCHECK(id);
return GetOrAddElementData(id, ElementContext())
->AddElementActivatedCallback(callback);
}
ElementTracker::Subscription ElementTracker::AddElementHiddenCallback(
ElementIdentifier id,
ElementContext context,
Callback callback) {
DCHECK(id);
DCHECK(context);
return GetOrAddElementData(id, context)->AddElementHiddenCallback(callback);
}
ElementTracker::Subscription
ElementTracker::AddElementHiddenInAnyContextCallback(ElementIdentifier id,
Callback callback) {
DCHECK(id);
return GetOrAddElementData(id, ElementContext())
->AddElementHiddenCallback(callback);
}
ElementTracker::Subscription ElementTracker::AddCustomEventCallback(
CustomElementEventType event_type,
ElementContext context,
Callback callback) {
DCHECK(event_type);
DCHECK(context);
// Because custom event callbacks are indexed by event type (and because we
// use the same underlying type for both element ids and custom events), we
// can store both in the same lookup table.
return GetOrAddElementData(event_type, context)
->AddCustomEventCallback(callback);
}
ElementTracker::Subscription ElementTracker::AddCustomEventInAnyContextCallback(
CustomElementEventType event_type,
Callback callback) {
DCHECK(event_type);
// Because custom event callbacks are indexed by event type (and because we
// use the same underlying type for both element ids and custom events), we
// can store both in the same lookup table.
return GetOrAddElementData(event_type, ElementContext())
->AddCustomEventCallback(callback);
}
ElementTracker::ElementTracker()
: gc_(std::make_unique<GarbageCollector>(this)) {}
ElementTracker::~ElementTracker() = default;
void ElementTracker::NotifyElementShown(TrackedElement* element) {
notification_elements_.push_back(element);
auto& safe_element = notification_elements_.back();
// Prevent garbage collection of dead entries until after we send
// notifications and all callbacks happen.
GarbageCollector::Frame gc_frame(gc_.get());
ElementData* const element_data =
GetOrAddElementData(element->identifier(), element->context());
DCHECK(!element_data->HasElement(element));
element_data->NotifyElementShown(safe_element);
// Do "all contexts" notification:
if (safe_element) {
const auto it =
element_data_.find(LookupKey(element->identifier(), ElementContext()));
if (it != element_data_.end())
it->second.NotifyElementShown(safe_element);
}
// Do the "all elements" notification:
if (safe_element)
any_element_shown_callbacks_.Notify(element);
notification_elements_.pop_back();
}
void ElementTracker::NotifyElementActivated(TrackedElement* element) {
notification_elements_.push_back(element);
auto& safe_element = notification_elements_.back();
// Prevent garbage collection of dead entries until after we send
// notifications and all callbacks happen.
GarbageCollector::Frame gc_frame(gc_.get());
const auto it =
element_data_.find(LookupKey(element->identifier(), element->context()));
CHECK(it != element_data_.end());
it->second.NotifyElementActivated(safe_element);
// Do "all contexts" notification:
if (safe_element) {
const auto all_it =
element_data_.find(LookupKey(element->identifier(), ElementContext()));
if (all_it != element_data_.end()) {
all_it->second.NotifyElementActivated(safe_element);
}
}
notification_elements_.pop_back();
}
void ElementTracker::NotifyElementHidden(TrackedElement* element) {
// Clear out any elements we're in the process of sending events for.
for (auto& safe_element : notification_elements_) {
if (safe_element == element)
safe_element = nullptr;
}
// Prevent garbage collection of dead entries until after we send
// notifications and all callbacks happen.
GarbageCollector::Frame gc_frame(gc_.get());
// Call context-specific callbacks and erase entry.
const auto it =
element_data_.find(LookupKey(element->identifier(), element->context()));
CHECK(it != element_data_.end());
ElementData* const data = &it->second;
data->NotifyElementHidden(element);
gc_frame.Add(data);
// Call "in any context" callbacks.
const auto all_it =
element_data_.find(LookupKey(element->identifier(), ElementContext()));
if (all_it != element_data_.end()) {
all_it->second.NotifyElementHidden(element);
}
}
void ElementTracker::NotifyCustomEvent(TrackedElement* element,
CustomElementEventType event_type) {
// Prevent garbage collection of dead entries until after we send
// notifications and all callbacks happen.
GarbageCollector::Frame gc_frame(gc_.get());
// We'd like to verify that this element is valid, but don't need to expend
// the effort on an extra lookup if we're not doing checks.
#if DCHECK_IS_ON()
const auto entry =
element_data_.find(LookupKey(element->identifier(), element->context()));
DCHECK(entry != element_data_.end() && entry->second.HasElement(element));
#endif
notification_elements_.push_back(element);
auto& safe_element = notification_elements_.back();
// Since event types are identifiers, we store callbacks by event type rather
// than element identifier.
const auto it = element_data_.find(LookupKey(event_type, element->context()));
// If we don't find a match, that's fine; it means nobody was listening for
// that event type.
if (it != element_data_.end()) {
it->second.NotifyCustomEvent(safe_element);
}
// Do "all contexts" notification:
const auto all_it =
element_data_.find(LookupKey(event_type, ElementContext()));
if (all_it != element_data_.end()) {
all_it->second.NotifyCustomEvent(safe_element);
}
notification_elements_.pop_back();
}
ElementTracker::ElementData* ElementTracker::GetOrAddElementData(
ElementIdentifier id,
ElementContext context) {
const LookupKey key(id, context);
const auto [it, added] = element_data_.try_emplace(key, this, id, context);
// This might be the first time we've referenced this identifier, so make
// sure it's registered.
if (added)
ElementIdentifier::RegisterKnownIdentifier(id);
return &it->second;
}
void ElementTracker::MaybeCleanup(ElementData* data) {
GarbageCollector::Frame gc_frame(gc_.get());
gc_frame.Add(data);
}
SafeElementReference::SafeElementReference() = default;
SafeElementReference::SafeElementReference(TrackedElement* element)
: element_(element) {
Subscribe();
}
SafeElementReference::SafeElementReference(SafeElementReference&& other)
: element_(other.element_) {
// Have to rebind instead of moving the subscription since the other
// reference's this pointer is bound.
Subscribe();
other.subscription_ = ElementTracker::Subscription();
other.element_ = nullptr;
}
SafeElementReference::SafeElementReference(const SafeElementReference& other)
: element_(other.element_) {
Subscribe();
}
SafeElementReference& SafeElementReference::operator=(TrackedElement* el) {
if (element_ != el) {
element_ = el;
Subscribe();
}
return *this;
}
SafeElementReference& SafeElementReference::operator=(
SafeElementReference&& other) {
if (&other != this) {
element_ = other.element_;
// Have to rebind instead of moving the subscription since the other
// reference's this pointer is bound.
Subscribe();
other.subscription_ = ElementTracker::Subscription();
other.element_ = nullptr;
}
return *this;
}
SafeElementReference& SafeElementReference::operator=(
const SafeElementReference& other) {
if (&other != this) {
element_ = other.element_;
Subscribe();
}
return *this;
}
SafeElementReference::~SafeElementReference() = default;
void SafeElementReference::Subscribe() {
if (!element_) {
if (subscription_)
subscription_ = ElementTracker::Subscription();
return;
}
subscription_ = ElementTracker::GetElementTracker()->AddElementHiddenCallback(
element_->identifier(), element_->context(),
base::BindRepeating(&SafeElementReference::OnElementHidden,
base::Unretained(this)));
}
void SafeElementReference::OnElementHidden(TrackedElement* element) {
if (element != element_)
return;
subscription_ = ElementTracker::Subscription();
element_ = nullptr;
}
} // namespace ui
|