EventDispatcher.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #include "EventDispatcher.h"
  2. #include "../../Include/RmlUi/Core/Element.h"
  3. #include "../../Include/RmlUi/Core/Event.h"
  4. #include "../../Include/RmlUi/Core/EventListener.h"
  5. #include "../../Include/RmlUi/Core/Factory.h"
  6. #include "EventSpecification.h"
  7. #include <algorithm>
  8. #include <limits>
  9. namespace Rml {
  10. bool operator==(EventListenerEntry a, EventListenerEntry b)
  11. {
  12. return a.id == b.id && a.in_capture_phase == b.in_capture_phase && a.listener == b.listener;
  13. }
  14. bool operator!=(EventListenerEntry a, EventListenerEntry b)
  15. {
  16. return !(a == b);
  17. }
  18. struct CompareId {
  19. bool operator()(EventListenerEntry a, EventListenerEntry b) const { return a.id < b.id; }
  20. };
  21. struct CompareIdPhase {
  22. bool operator()(EventListenerEntry a, EventListenerEntry b) const
  23. {
  24. return std::tie(a.id, a.in_capture_phase) < std::tie(b.id, b.in_capture_phase);
  25. }
  26. };
  27. EventDispatcher::EventDispatcher(Element* _element) : element(_element) {}
  28. EventDispatcher::~EventDispatcher()
  29. {
  30. // Detach from all event dispatchers
  31. for (const auto& event : listeners)
  32. event.listener->OnDetach(element);
  33. }
  34. void EventDispatcher::AttachEvent(const EventId id, EventListener* listener, const bool in_capture_phase)
  35. {
  36. const EventListenerEntry entry(id, listener, in_capture_phase);
  37. // The entries are sorted by (id,phase). Find the bounds of this sort, then find the entry.
  38. const auto range = std::equal_range(listeners.cbegin(), listeners.cend(), entry, CompareIdPhase());
  39. const auto matching_entry_it = std::find(range.first, range.second, entry);
  40. if (matching_entry_it == range.second)
  41. {
  42. listeners.emplace(range.second, entry);
  43. listener->OnAttach(element);
  44. }
  45. }
  46. void EventDispatcher::DetachEvent(const EventId id, EventListener* listener, const bool in_capture_phase)
  47. {
  48. const auto listenerIt = std::find(listeners.cbegin(), listeners.cend(), EventListenerEntry(id, listener, in_capture_phase));
  49. if (listenerIt != listeners.cend())
  50. {
  51. listeners.erase(listenerIt);
  52. listener->OnDetach(element);
  53. }
  54. }
  55. void EventDispatcher::DetachAllEvents()
  56. {
  57. for (const auto& event : listeners)
  58. event.listener->OnDetach(element);
  59. listeners.clear();
  60. for (int i = 0; i < element->GetNumChildren(true); ++i)
  61. element->GetChild(i)->GetEventDispatcher()->DetachAllEvents();
  62. }
  63. /*
  64. CollectedListener
  65. When dispatching an event we collect all possible event listeners to execute.
  66. They are stored in observer pointers, so that we can safely check if they have been destroyed since the previous listener execution.
  67. */
  68. struct CollectedListener {
  69. CollectedListener(Element* _element, EventListener* _listener, int dom_distance_from_target, bool in_capture_phase) :
  70. element(_element->GetObserverPtr()), listener(_listener->GetObserverPtr())
  71. {
  72. sort = dom_distance_from_target * (in_capture_phase ? -1 : 1);
  73. }
  74. // The sort value is determined by the distance of the element to the target element in the DOM.
  75. // Capture phase is given negative values.
  76. int sort = 0;
  77. ObserverPtr<Element> element;
  78. ObserverPtr<EventListener> listener;
  79. // Default actions are returned by EventPhase::None.
  80. EventPhase GetPhase() const { return sort < 0 ? EventPhase::Capture : (sort == 0 ? EventPhase::Target : EventPhase::Bubble); }
  81. bool operator<(const CollectedListener& other) const { return sort < other.sort; }
  82. };
  83. bool EventDispatcher::DispatchEvent(Element* target_element, const EventId id, const String& type, const Dictionary& parameters,
  84. const bool interruptible, const bool bubbles, const DefaultActionPhase default_action_phase)
  85. {
  86. RMLUI_ASSERTMSG(!((int)default_action_phase & (int)EventPhase::Capture),
  87. "We assume here that the default action phases cannot include capture phase.");
  88. Vector<CollectedListener> listeners;
  89. Vector<ObserverPtr<Element>> default_action_elements;
  90. const EventPhase phases_to_execute = EventPhase((int)EventPhase::Capture | (int)EventPhase::Target | (bubbles ? (int)EventPhase::Bubble : 0));
  91. // Walk the DOM tree from target to root, collecting all possible listeners and elements with default actions in the process.
  92. int dom_distance_from_target = 0;
  93. Element* walk_element = target_element;
  94. while (walk_element)
  95. {
  96. EventDispatcher* dispatcher = walk_element->GetEventDispatcher();
  97. dispatcher->CollectListeners(dom_distance_from_target, id, phases_to_execute, listeners);
  98. if (dom_distance_from_target == 0)
  99. {
  100. if ((int)default_action_phase & (int)EventPhase::Target)
  101. default_action_elements.push_back(walk_element->GetObserverPtr());
  102. }
  103. else if ((int)default_action_phase & (int)EventPhase::Bubble)
  104. {
  105. default_action_elements.push_back(walk_element->GetObserverPtr());
  106. }
  107. walk_element = walk_element->GetParentNode();
  108. dom_distance_from_target += 1;
  109. }
  110. if (listeners.empty() && default_action_elements.empty())
  111. return true;
  112. // Use stable_sort so that the order of the listeners in a given element is maintained.
  113. std::stable_sort(listeners.begin(), listeners.end());
  114. // Instance event
  115. EventPtr event = Factory::InstanceEvent(target_element, id, type, parameters, interruptible);
  116. if (!event)
  117. return false;
  118. auto previous_sort_value = std::numeric_limits<int>::max();
  119. // Process the event in each listener.
  120. for (const auto& listener_desc : listeners)
  121. {
  122. Element* element = listener_desc.element.get();
  123. EventListener* listener = listener_desc.listener.get();
  124. if (listener_desc.sort != previous_sort_value)
  125. {
  126. // New sort values represent a new level in the DOM, thus, set the new element and possibly new phase.
  127. if (!event->IsPropagating())
  128. break;
  129. event->SetCurrentElement(element);
  130. event->SetPhase(listener_desc.GetPhase());
  131. previous_sort_value = listener_desc.sort;
  132. }
  133. // We only submit the event if both the current element and listener are still alive.
  134. if (element && listener)
  135. {
  136. listener->ProcessEvent(*event);
  137. }
  138. if (!event->IsImmediatePropagating())
  139. break;
  140. }
  141. // Process the default actions.
  142. for (auto& element_ptr : default_action_elements)
  143. {
  144. if (!event->IsPropagating())
  145. break;
  146. if (Element* element = element_ptr.get())
  147. {
  148. event->SetCurrentElement(element);
  149. event->SetPhase(element == target_element ? EventPhase::Target : EventPhase::Bubble);
  150. element->ProcessDefaultAction(*event);
  151. }
  152. }
  153. bool propagating = event->IsPropagating();
  154. return propagating;
  155. }
  156. void EventDispatcher::CollectListeners(int dom_distance_from_target, const EventId event_id, const EventPhase event_executes_in_phases,
  157. Vector<CollectedListener>& collect_listeners)
  158. {
  159. // Find all the entries with a matching id, given that listeners are sorted by id first.
  160. Listeners::iterator begin, end;
  161. std::tie(begin, end) = std::equal_range(listeners.begin(), listeners.end(), EventListenerEntry(event_id, nullptr, false), CompareId());
  162. const bool in_target_phase = (dom_distance_from_target == 0);
  163. if (in_target_phase)
  164. {
  165. // Listeners always attach to target phase, but make sure the event can actually execute in target phase.
  166. if ((int)event_executes_in_phases & (int)EventPhase::Target)
  167. {
  168. for (auto it = begin; it != end; ++it)
  169. collect_listeners.emplace_back(element, it->listener, dom_distance_from_target, false);
  170. }
  171. }
  172. else
  173. {
  174. // Iterate through all the listeners and collect those matching the event execution phase.
  175. for (auto it = begin; it != end; ++it)
  176. {
  177. // Listeners will either attach to capture or bubble phase, make sure the event can execute in the same phase.
  178. const EventPhase listener_executes_in_phase = (it->in_capture_phase ? EventPhase::Capture : EventPhase::Bubble);
  179. if ((int)event_executes_in_phases & (int)listener_executes_in_phase)
  180. collect_listeners.emplace_back(element, it->listener, dom_distance_from_target, it->in_capture_phase);
  181. }
  182. }
  183. }
  184. String EventDispatcher::ToString() const
  185. {
  186. String result;
  187. if (listeners.empty())
  188. return result;
  189. auto add_to_result = [&result](EventId id, int count) {
  190. const EventSpecification& specification = EventSpecificationInterface::Get(id);
  191. result += CreateString("%s (%d), ", specification.type.c_str(), count);
  192. };
  193. EventId previous_id = listeners[0].id;
  194. int count = 0;
  195. for (const auto& listener : listeners)
  196. {
  197. if (listener.id != previous_id)
  198. {
  199. add_to_result(previous_id, count);
  200. previous_id = listener.id;
  201. count = 0;
  202. }
  203. count++;
  204. }
  205. if (count > 0)
  206. add_to_result(previous_id, count);
  207. if (result.size() > 2)
  208. result.resize(result.size() - 2);
  209. return result;
  210. }
  211. } // namespace Rml