EventDispatcher.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 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 "precompiled.h"
  29. #include "EventDispatcher.h"
  30. #include "../../Include/RmlUi/Core/Element.h"
  31. #include "../../Include/RmlUi/Core/Event.h"
  32. #include "../../Include/RmlUi/Core/EventListener.h"
  33. #include "../../Include/RmlUi/Core/Factory.h"
  34. #include "EventSpecification.h"
  35. namespace Rml {
  36. namespace Core {
  37. bool operator==(EventListenerEntry a, EventListenerEntry b) { return a.id == b.id && a.in_capture_phase == b.in_capture_phase && a.listener == b.listener; }
  38. bool operator!=(EventListenerEntry a, EventListenerEntry b) { return !(a == b); }
  39. struct CompareId {
  40. bool operator()(EventListenerEntry a, EventListenerEntry b) const { return a.id < b.id; }
  41. };
  42. struct CompareIdPhase {
  43. bool operator()(EventListenerEntry a, EventListenerEntry b) const { return std::tie(a.id, a.in_capture_phase) < std::tie(b.id, b.in_capture_phase); }
  44. };
  45. EventDispatcher::EventDispatcher(Element* _element)
  46. {
  47. element = _element;
  48. }
  49. EventDispatcher::~EventDispatcher()
  50. {
  51. // Detach from all event dispatchers
  52. for (const auto& event : listeners)
  53. event.listener->OnDetach(element);
  54. }
  55. void EventDispatcher::AttachEvent(EventId id, EventListener* listener, bool in_capture_phase)
  56. {
  57. EventListenerEntry entry(id, listener, in_capture_phase);
  58. // The entries are sorted by (id,phase). Find the bounds of this sort, then find the entry.
  59. auto range = std::equal_range(listeners.begin(), listeners.end(), entry, CompareIdPhase());
  60. auto it = std::find(range.first, range.second, entry);
  61. if(it == range.second)
  62. {
  63. // No existing entry found, add it to the end of the (id, phase) range
  64. listeners.emplace(it, entry);
  65. listener->OnAttach(element);
  66. }
  67. }
  68. void EventDispatcher::DetachEvent(EventId id, EventListener* listener, bool in_capture_phase)
  69. {
  70. EventListenerEntry entry(id, listener, in_capture_phase);
  71. // The entries are sorted by (id,phase). Find the bounds of this sort, then find the entry.
  72. // We could also just do a linear search over all the entries, which might be faster for low number of entries.
  73. auto range = std::equal_range(listeners.begin(), listeners.end(), entry, CompareIdPhase());
  74. auto it = std::find(range.first, range.second, entry);
  75. if (it != range.second)
  76. {
  77. // We found our listener, remove it
  78. listeners.erase(it);
  79. listener->OnDetach(element);
  80. }
  81. }
  82. // Detaches all events from this dispatcher and all child dispatchers.
  83. void EventDispatcher::DetachAllEvents()
  84. {
  85. for (const auto& event : listeners)
  86. event.listener->OnDetach(element);
  87. listeners.clear();
  88. for (int i = 0; i < element->GetNumChildren(true); ++i)
  89. element->GetChild(i)->GetEventDispatcher()->DetachAllEvents();
  90. }
  91. /*
  92. EventListenersToExecute
  93. When dispatching an event we collect all possible event listeners and default actions to execute.
  94. They are stored in observer pointers, so that we can safely check if they have been destroyed since the previous listener execution.
  95. */
  96. struct EventListenersToExecute {
  97. EventListenersToExecute(Element* _element, EventListener* _listener, int dom_distance_from_target, bool in_capture_phase) : element(_element->GetObserverPtr()), listener(_listener ? _listener->GetObserverPtr() : nullptr)
  98. {
  99. sort = dom_distance_from_target * (in_capture_phase ? -1 : 1);
  100. if (!_listener)
  101. {
  102. // No listener means default action
  103. sort += DefaultActionAdd;
  104. }
  105. }
  106. static constexpr int DefaultActionMin = 50'000;
  107. static constexpr int DefaultActionAdd = 100'000;
  108. // The sort value is determined by the distance of the element to the target element in the DOM.
  109. // Capture phase is given negative values. Default actions add the large number DefaultActionAdd so they are sorted last.
  110. int sort = 0;
  111. ObserverPtr<Element> element;
  112. ObserverPtr<EventListener> listener;
  113. // Default actions are returned by EventPhase::None.
  114. EventPhase GetPhase() const { return sort < 0 ? EventPhase::Capture : (sort == 0 ? EventPhase::Target : (sort >= DefaultActionMin ? EventPhase::None : EventPhase::Bubble)); }
  115. bool operator<(const EventListenersToExecute& other) const {
  116. return sort < other.sort;
  117. }
  118. };
  119. bool EventDispatcher::DispatchEvent(Element* target_element, EventId id, const String& type, const Dictionary& parameters, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase)
  120. {
  121. std::vector<EventListenersToExecute> listeners;
  122. const EventPhase phases_to_execute = EventPhase((int)EventPhase::Capture | (int)EventPhase::Target | (bubbles ? (int)EventPhase::Bubble : 0));
  123. // Walk the DOM tree from target to root, collecting all possible listeners and elements with default actions in the process.
  124. int dom_distance_from_target = 0;
  125. Element* walk_element = target_element;
  126. while (walk_element)
  127. {
  128. EventDispatcher* dispatcher = walk_element->GetEventDispatcher();
  129. dispatcher->CollectListeners(dom_distance_from_target, id, phases_to_execute, default_action_phase, listeners);
  130. walk_element = walk_element->GetParentNode();
  131. dom_distance_from_target += 1;
  132. }
  133. // Use stable_sort so that the order of the listeners in a given element is maintained.
  134. std::stable_sort(listeners.begin(), listeners.end());
  135. if (listeners.empty())
  136. return true;
  137. // Instance event
  138. EventPtr event = Factory::InstanceEvent(target_element, id, type, parameters, interruptible);
  139. if (!event)
  140. return false;
  141. int previous_sort_value = INT_MAX;
  142. EventPhase current_phase = EventPhase::None;
  143. // Process the event in each listener.
  144. for (auto& listener_desc : listeners)
  145. {
  146. Element* element = listener_desc.element.get();
  147. EventListener* listener = listener_desc.listener.get();
  148. if (listener_desc.sort != previous_sort_value)
  149. {
  150. // New sort values represent a new level in the DOM, thus, set the new element and possibly new phase.
  151. if (!event->IsPropagating())
  152. break;
  153. event->SetCurrentElement(element);
  154. current_phase = listener_desc.GetPhase();
  155. event->SetPhase(current_phase);
  156. previous_sort_value = listener_desc.sort;
  157. }
  158. if (element && listener)
  159. {
  160. // We have a valid event listener
  161. listener->ProcessEvent(*event);
  162. }
  163. else if (element && current_phase == EventPhase::None)
  164. {
  165. // EventPhase::None means default actions. We assume default actions only execute in either target or bubble phase.
  166. event->SetPhase(element == target_element ? EventPhase::Target : EventPhase::Bubble);
  167. element->ProcessDefaultAction(*event);
  168. }
  169. if (!event->IsImmediatePropagating())
  170. break;
  171. }
  172. bool propagating = event->IsPropagating();
  173. return propagating;
  174. }
  175. 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<EventListenersToExecute>& collect_listeners)
  176. {
  177. const bool in_target_phase = (dom_distance_from_target == 0);
  178. // Find all the entries with a matching id, given that listeners are sorted by id first.
  179. Listeners::iterator begin, end;
  180. std::tie(begin, end) = std::equal_range(listeners.begin(), listeners.end(), EventListenerEntry(event_id, nullptr, false), CompareId());
  181. for (auto it = begin; it != end; ++it)
  182. {
  183. if (in_target_phase)
  184. {
  185. // Listeners always attach to target phase, but make sure event can actually execute in target phase.
  186. if ((int)event_executes_in_phases & (int)EventPhase::Target)
  187. collect_listeners.emplace_back(element, it->listener, dom_distance_from_target, it->in_capture_phase);
  188. }
  189. else
  190. {
  191. // Listeners will either attach to capture or bubble phase, make sure event can execute in the same phase.
  192. const EventPhase listener_executes_in_phase = (it->in_capture_phase ? EventPhase::Capture : EventPhase::Bubble);
  193. if ((int)event_executes_in_phases & (int)listener_executes_in_phase)
  194. collect_listeners.emplace_back(element, it->listener, dom_distance_from_target, it->in_capture_phase);
  195. }
  196. }
  197. RMLUI_ASSERTMSG(!((int)default_action_phase & (int)EventPhase::Capture), "We assume here that the default action phases cannot include capture phase.");
  198. // Add the default action
  199. EventPhase phase_for_default_action = (in_target_phase ? EventPhase::Target : EventPhase::Bubble);
  200. if ((int)phase_for_default_action & (int)default_action_phase)
  201. collect_listeners.emplace_back(element, nullptr, dom_distance_from_target, false);
  202. }
  203. String EventDispatcher::ToString() const
  204. {
  205. String result;
  206. if (listeners.empty())
  207. return result;
  208. auto add_to_result = [&result](EventId id, int count) {
  209. const EventSpecification& specification = EventSpecificationInterface::Get(id);
  210. result += CreateString(specification.type.size() + 32, "%s (%d), ", specification.type.c_str(), count);
  211. };
  212. EventId previous_id = listeners[0].id;
  213. int count = 0;
  214. for (const auto& listener : listeners)
  215. {
  216. if (listener.id != previous_id)
  217. {
  218. add_to_result(previous_id, count);
  219. previous_id = listener.id;
  220. count = 0;
  221. }
  222. count++;
  223. }
  224. if (count > 0)
  225. add_to_result(previous_id, count);
  226. if (result.size() > 2)
  227. result.resize(result.size() - 2);
  228. return result;
  229. }
  230. }
  231. }