/*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
* Copyright (c) 2019 The RmlUi Team, and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "precompiled.h"
#include "EventDispatcher.h"
#include "../../Include/RmlUi/Core/Element.h"
#include "../../Include/RmlUi/Core/Event.h"
#include "../../Include/RmlUi/Core/EventListener.h"
#include "../../Include/RmlUi/Core/Factory.h"
#include "EventSpecification.h"
namespace Rml {
namespace Core {
bool operator==(EventListenerEntry a, EventListenerEntry b) { return a.id == b.id && a.in_capture_phase == b.in_capture_phase && a.listener == b.listener; }
bool operator!=(EventListenerEntry a, EventListenerEntry b) { return !(a == b); }
struct CompareId {
bool operator()(EventListenerEntry a, EventListenerEntry b) const { return a.id < b.id; }
};
struct CompareIdPhase {
bool operator()(EventListenerEntry a, EventListenerEntry b) const { return std::tie(a.id, a.in_capture_phase) < std::tie(b.id, b.in_capture_phase); }
};
EventDispatcher::EventDispatcher(Element* _element)
{
element = _element;
}
EventDispatcher::~EventDispatcher()
{
// Detach from all event dispatchers
for (const auto& event : listeners)
event.listener->OnDetach(element);
}
void EventDispatcher::AttachEvent(EventId id, EventListener* listener, bool in_capture_phase)
{
EventListenerEntry entry(id, listener, in_capture_phase);
// The entries are sorted by (id,phase). Find the bounds of this sort, then find the entry.
auto range = std::equal_range(listeners.begin(), listeners.end(), entry, CompareIdPhase());
auto it = std::find(range.first, range.second, entry);
if(it == range.second)
{
// No existing entry found, add it to the end of the (id, phase) range
listeners.emplace(it, entry);
listener->OnAttach(element);
}
}
void EventDispatcher::DetachEvent(EventId id, EventListener* listener, bool in_capture_phase)
{
EventListenerEntry entry(id, listener, in_capture_phase);
// The entries are sorted by (id,phase). Find the bounds of this sort, then find the entry.
// We could also just do a linear search over all the entries, which might be faster for low number of entries.
auto range = std::equal_range(listeners.begin(), listeners.end(), entry, CompareIdPhase());
auto it = std::find(range.first, range.second, entry);
if (it != range.second)
{
// We found our listener, remove it
listeners.erase(it);
listener->OnDetach(element);
}
}
// Detaches all events from this dispatcher and all child dispatchers.
void EventDispatcher::DetachAllEvents()
{
for (const auto& event : listeners)
event.listener->OnDetach(element);
listeners.clear();
for (int i = 0; i < element->GetNumChildren(true); ++i)
element->GetChild(i)->GetEventDispatcher()->DetachAllEvents();
}
/*
EventListenersToExecute
When dispatching an event we collect all possible event listeners and default actions to execute.
They are stored in observer pointers, so that we can safely check if they have been destroyed since the previous listener execution.
*/
struct EventListenersToExecute {
EventListenersToExecute(Element* _element, EventListener* _listener, int dom_distance_from_target, bool in_capture_phase) : element(_element->GetObserverPtr()), listener(_listener ? _listener->GetObserverPtr() : nullptr)
{
sort = dom_distance_from_target * (in_capture_phase ? -1 : 1);
if (!_listener)
{
// No listener means default action
sort += DefaultActionAdd;
}
}
static constexpr int DefaultActionMin = 50'000;
static constexpr int DefaultActionAdd = 100'000;
// The sort value is determined by the distance of the element to the target element in the DOM.
// Capture phase is given negative values. Default actions add the large number DefaultActionAdd so they are sorted last.
int sort = 0;
ObserverPtr element;
ObserverPtr listener;
// Default actions are returned by EventPhase::None.
EventPhase GetPhase() const { return sort < 0 ? EventPhase::Capture : (sort == 0 ? EventPhase::Target : (sort >= DefaultActionMin ? EventPhase::None : EventPhase::Bubble)); }
bool operator<(const EventListenersToExecute& other) const {
return sort < other.sort;
}
};
bool EventDispatcher::DispatchEvent(Element* target_element, EventId id, const String& type, const Dictionary& parameters, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase)
{
std::vector listeners;
const EventPhase phases_to_execute = EventPhase((int)EventPhase::Capture | (int)EventPhase::Target | (bubbles ? (int)EventPhase::Bubble : 0));
// Walk the DOM tree from target to root, collecting all possible listeners and elements with default actions in the process.
int dom_distance_from_target = 0;
Element* walk_element = target_element;
while (walk_element)
{
EventDispatcher* dispatcher = walk_element->GetEventDispatcher();
dispatcher->CollectListeners(dom_distance_from_target, id, phases_to_execute, default_action_phase, listeners);
walk_element = walk_element->GetParentNode();
dom_distance_from_target += 1;
}
// Use stable_sort so that the order of the listeners in a given element is maintained.
std::stable_sort(listeners.begin(), listeners.end());
if (listeners.empty())
return true;
// Instance event
EventPtr event = Factory::InstanceEvent(target_element, id, type, parameters, interruptible);
if (!event)
return false;
int previous_sort_value = INT_MAX;
EventPhase current_phase = EventPhase::None;
// Process the event in each listener.
for (auto& listener_desc : listeners)
{
Element* element = listener_desc.element.get();
EventListener* listener = listener_desc.listener.get();
if (listener_desc.sort != previous_sort_value)
{
// New sort values represent a new level in the DOM, thus, set the new element and possibly new phase.
if (!event->IsPropagating())
break;
event->SetCurrentElement(element);
current_phase = listener_desc.GetPhase();
event->SetPhase(current_phase);
previous_sort_value = listener_desc.sort;
}
if (element && listener)
{
// We have a valid event listener
listener->ProcessEvent(*event);
}
else if (element && current_phase == EventPhase::None)
{
// EventPhase::None means default actions. We assume default actions only execute in either target or bubble phase.
event->SetPhase(element == target_element ? EventPhase::Target : EventPhase::Bubble);
element->ProcessDefaultAction(*event);
}
if (!event->IsImmediatePropagating())
break;
}
bool propagating = event->IsPropagating();
return propagating;
}
void EventDispatcher::CollectListeners(int dom_distance_from_target, const EventId event_id, const EventPhase event_executes_in_phases, const DefaultActionPhase default_action_phase, std::vector& collect_listeners)
{
const bool in_target_phase = (dom_distance_from_target == 0);
// Find all the entries with a matching id, given that listeners are sorted by id first.
Listeners::iterator begin, end;
std::tie(begin, end) = std::equal_range(listeners.begin(), listeners.end(), EventListenerEntry(event_id, nullptr, false), CompareId());
for (auto it = begin; it != end; ++it)
{
if (in_target_phase)
{
// Listeners always attach to target phase, but make sure event can actually execute in target phase.
if ((int)event_executes_in_phases & (int)EventPhase::Target)
collect_listeners.emplace_back(element, it->listener, dom_distance_from_target, it->in_capture_phase);
}
else
{
// Listeners will either attach to capture or bubble phase, make sure event can execute in the same phase.
const EventPhase listener_executes_in_phase = (it->in_capture_phase ? EventPhase::Capture : EventPhase::Bubble);
if ((int)event_executes_in_phases & (int)listener_executes_in_phase)
collect_listeners.emplace_back(element, it->listener, dom_distance_from_target, it->in_capture_phase);
}
}
RMLUI_ASSERTMSG(!((int)default_action_phase & (int)EventPhase::Capture), "We assume here that the default action phases cannot include capture phase.");
// Add the default action
EventPhase phase_for_default_action = (in_target_phase ? EventPhase::Target : EventPhase::Bubble);
if ((int)phase_for_default_action & (int)default_action_phase)
collect_listeners.emplace_back(element, nullptr, dom_distance_from_target, false);
}
String EventDispatcher::ToString() const
{
String result;
if (listeners.empty())
return result;
auto add_to_result = [&result](EventId id, int count) {
const EventSpecification& specification = EventSpecificationInterface::Get(id);
result += CreateString(specification.type.size() + 32, "%s (%d), ", specification.type.c_str(), count);
};
EventId previous_id = listeners[0].id;
int count = 0;
for (const auto& listener : listeners)
{
if (listener.id != previous_id)
{
add_to_result(previous_id, count);
previous_id = listener.id;
count = 0;
}
count++;
}
if (count > 0)
add_to_result(previous_id, count);
if (result.size() > 2)
result.resize(result.size() - 2);
return result;
}
}
}