EventDispatcher.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "EventDispatcher.h"
  29. #include "../../Include/RmlUi/Core/Element.h"
  30. #include "../../Include/RmlUi/Core/Event.h"
  31. #include "../../Include/RmlUi/Core/EventListener.h"
  32. #include "../../Include/RmlUi/Core/Factory.h"
  33. #include "EventSpecification.h"
  34. #include <algorithm>
  35. #include <limits>
  36. namespace Rml {
  37. bool operator==(EventListenerEntry a, EventListenerEntry b)
  38. {
  39. return a.id == b.id && a.in_capture_phase == b.in_capture_phase && a.listener == b.listener;
  40. }
  41. bool operator!=(EventListenerEntry a, EventListenerEntry b)
  42. {
  43. return !(a == b);
  44. }
  45. struct CompareId {
  46. bool operator()(EventListenerEntry a, EventListenerEntry b) const { return a.id < b.id; }
  47. };
  48. struct CompareIdPhase {
  49. bool operator()(EventListenerEntry a, EventListenerEntry b) const
  50. {
  51. return std::tie(a.id, a.in_capture_phase) < std::tie(b.id, b.in_capture_phase);
  52. }
  53. };
  54. EventDispatcher::EventDispatcher(Element* _element) : element(_element) {}
  55. EventDispatcher::~EventDispatcher()
  56. {
  57. // Detach from all event dispatchers
  58. for (const auto& event : listeners)
  59. event.listener->OnDetach(element);
  60. }
  61. void EventDispatcher::AttachEvent(const EventId id, EventListener* listener, const bool in_capture_phase)
  62. {
  63. const EventListenerEntry entry(id, listener, in_capture_phase);
  64. // The entries are sorted by (id,phase). Find the bounds of this sort, then find the entry.
  65. const auto range = std::equal_range(listeners.cbegin(), listeners.cend(), entry, CompareIdPhase());
  66. const auto matching_entry_it = std::find(range.first, range.second, entry);
  67. if (matching_entry_it == range.second)
  68. {
  69. listeners.emplace(range.second, entry);
  70. listener->OnAttach(element);
  71. }
  72. }
  73. void EventDispatcher::DetachEvent(const EventId id, EventListener* listener, const bool in_capture_phase)
  74. {
  75. const auto listenerIt = std::find(listeners.cbegin(), listeners.cend(), EventListenerEntry(id, listener, in_capture_phase));
  76. if (listenerIt != listeners.cend())
  77. {
  78. listeners.erase(listenerIt);
  79. listener->OnDetach(element);
  80. }
  81. }
  82. void EventDispatcher::DetachAllEvents()
  83. {
  84. for (const auto& event : listeners)
  85. event.listener->OnDetach(element);
  86. listeners.clear();
  87. for (int i = 0; i < element->GetNumChildren(true); ++i)
  88. element->GetChild(i)->GetEventDispatcher()->DetachAllEvents();
  89. }
  90. /*
  91. CollectedListener
  92. When dispatching an event we collect all possible event listeners to execute.
  93. They are stored in observer pointers, so that we can safely check if they have been destroyed since the previous listener execution.
  94. */
  95. struct CollectedListener {
  96. CollectedListener(Element* _element, EventListener* _listener, int dom_distance_from_target, bool in_capture_phase) :
  97. element(_element->GetObserverPtr()), listener(_listener->GetObserverPtr())
  98. {
  99. sort = dom_distance_from_target * (in_capture_phase ? -1 : 1);
  100. }
  101. // The sort value is determined by the distance of the element to the target element in the DOM.
  102. // Capture phase is given negative values.
  103. int sort = 0;
  104. ObserverPtr<Element> element;
  105. ObserverPtr<EventListener> listener;
  106. // Default actions are returned by EventPhase::None.
  107. EventPhase GetPhase() const { return sort < 0 ? EventPhase::Capture : (sort == 0 ? EventPhase::Target : EventPhase::Bubble); }
  108. bool operator<(const CollectedListener& other) const { return sort < other.sort; }
  109. };
  110. bool EventDispatcher::DispatchEvent(Element* target_element, const EventId id, const String& type, const Dictionary& parameters,
  111. const bool interruptible, const bool bubbles, const DefaultActionPhase default_action_phase)
  112. {
  113. RMLUI_ASSERTMSG(!((int)default_action_phase & (int)EventPhase::Capture),
  114. "We assume here that the default action phases cannot include capture phase.");
  115. Vector<CollectedListener> listeners;
  116. Vector<ObserverPtr<Element>> default_action_elements;
  117. const EventPhase phases_to_execute = EventPhase((int)EventPhase::Capture | (int)EventPhase::Target | (bubbles ? (int)EventPhase::Bubble : 0));
  118. // Walk the DOM tree from target to root, collecting all possible listeners and elements with default actions in the process.
  119. int dom_distance_from_target = 0;
  120. Element* walk_element = target_element;
  121. while (walk_element)
  122. {
  123. EventDispatcher* dispatcher = walk_element->GetEventDispatcher();
  124. dispatcher->CollectListeners(dom_distance_from_target, id, phases_to_execute, listeners);
  125. if (dom_distance_from_target == 0)
  126. {
  127. if ((int)default_action_phase & (int)EventPhase::Target)
  128. default_action_elements.push_back(walk_element->GetObserverPtr());
  129. }
  130. else if ((int)default_action_phase & (int)EventPhase::Bubble)
  131. {
  132. default_action_elements.push_back(walk_element->GetObserverPtr());
  133. }
  134. walk_element = walk_element->GetParentNode();
  135. dom_distance_from_target += 1;
  136. }
  137. if (listeners.empty() && default_action_elements.empty())
  138. return true;
  139. // Use stable_sort so that the order of the listeners in a given element is maintained.
  140. std::stable_sort(listeners.begin(), listeners.end());
  141. // Instance event
  142. EventPtr event = Factory::InstanceEvent(target_element, id, type, parameters, interruptible);
  143. if (!event)
  144. return false;
  145. auto previous_sort_value = std::numeric_limits<int>::max();
  146. // Process the event in each listener.
  147. for (const auto& listener_desc : listeners)
  148. {
  149. Element* element = listener_desc.element.get();
  150. EventListener* listener = listener_desc.listener.get();
  151. if (listener_desc.sort != previous_sort_value)
  152. {
  153. // New sort values represent a new level in the DOM, thus, set the new element and possibly new phase.
  154. if (!event->IsPropagating())
  155. break;
  156. event->SetCurrentElement(element);
  157. event->SetPhase(listener_desc.GetPhase());
  158. previous_sort_value = listener_desc.sort;
  159. }
  160. // We only submit the event if both the current element and listener are still alive.
  161. if (element && listener)
  162. {
  163. listener->ProcessEvent(*event);
  164. }
  165. if (!event->IsImmediatePropagating())
  166. break;
  167. }
  168. // Process the default actions.
  169. for (auto& element_ptr : default_action_elements)
  170. {
  171. if (!event->IsPropagating())
  172. break;
  173. if (Element* element = element_ptr.get())
  174. {
  175. event->SetCurrentElement(element);
  176. event->SetPhase(element == target_element ? EventPhase::Target : EventPhase::Bubble);
  177. element->ProcessDefaultAction(*event);
  178. }
  179. }
  180. bool propagating = event->IsPropagating();
  181. return propagating;
  182. }
  183. void EventDispatcher::CollectListeners(int dom_distance_from_target, const EventId event_id, const EventPhase event_executes_in_phases,
  184. Vector<CollectedListener>& collect_listeners)
  185. {
  186. // Find all the entries with a matching id, given that listeners are sorted by id first.
  187. Listeners::iterator begin, end;
  188. std::tie(begin, end) = std::equal_range(listeners.begin(), listeners.end(), EventListenerEntry(event_id, nullptr, false), CompareId());
  189. const bool in_target_phase = (dom_distance_from_target == 0);
  190. if (in_target_phase)
  191. {
  192. // Listeners always attach to target phase, but make sure the event can actually execute in target phase.
  193. if ((int)event_executes_in_phases & (int)EventPhase::Target)
  194. {
  195. for (auto it = begin; it != end; ++it)
  196. collect_listeners.emplace_back(element, it->listener, dom_distance_from_target, false);
  197. }
  198. }
  199. else
  200. {
  201. // Iterate through all the listeners and collect those matching the event execution phase.
  202. for (auto it = begin; it != end; ++it)
  203. {
  204. // Listeners will either attach to capture or bubble phase, make sure the event can execute in the same phase.
  205. const EventPhase listener_executes_in_phase = (it->in_capture_phase ? EventPhase::Capture : EventPhase::Bubble);
  206. if ((int)event_executes_in_phases & (int)listener_executes_in_phase)
  207. collect_listeners.emplace_back(element, it->listener, dom_distance_from_target, it->in_capture_phase);
  208. }
  209. }
  210. }
  211. String EventDispatcher::ToString() const
  212. {
  213. String result;
  214. if (listeners.empty())
  215. return result;
  216. auto add_to_result = [&result](EventId id, int count) {
  217. const EventSpecification& specification = EventSpecificationInterface::Get(id);
  218. result += CreateString("%s (%d), ", specification.type.c_str(), count);
  219. };
  220. EventId previous_id = listeners[0].id;
  221. int count = 0;
  222. for (const auto& listener : listeners)
  223. {
  224. if (listener.id != previous_id)
  225. {
  226. add_to_result(previous_id, count);
  227. previous_id = listener.id;
  228. count = 0;
  229. }
  230. count++;
  231. }
  232. if (count > 0)
  233. add_to_result(previous_id, count);
  234. if (result.size() > 2)
  235. result.resize(result.size() - 2);
  236. return result;
  237. }
  238. } // namespace Rml