Context.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  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 "../../Include/RmlUi/Core/Context.h"
  29. #include "../../Include/RmlUi/Core/ContextInstancer.h"
  30. #include "../../Include/RmlUi/Core/Core.h"
  31. #include "../../Include/RmlUi/Core/DataModelHandle.h"
  32. #include "../../Include/RmlUi/Core/ElementDocument.h"
  33. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  34. #include "../../Include/RmlUi/Core/Factory.h"
  35. #include "../../Include/RmlUi/Core/Profiling.h"
  36. #include "../../Include/RmlUi/Core/RenderInterface.h"
  37. #include "../../Include/RmlUi/Core/StreamMemory.h"
  38. #include "../../Include/RmlUi/Core/SystemInterface.h"
  39. #include "../../Include/RmlUi/Core/StreamMemory.h"
  40. #include "DataModel.h"
  41. #include "EventDispatcher.h"
  42. #include "PluginRegistry.h"
  43. #include "StreamFile.h"
  44. #include <algorithm>
  45. #include <iterator>
  46. namespace Rml {
  47. static constexpr float DOUBLE_CLICK_TIME = 0.5f; // [s]
  48. static constexpr float DOUBLE_CLICK_MAX_DIST = 3.f; // [dp]
  49. Context::Context(const String& name) : name(name), dimensions(0, 0), density_independent_pixel_ratio(1.0f), mouse_position(0, 0), clip_origin(-1, -1), clip_dimensions(-1, -1)
  50. {
  51. instancer = nullptr;
  52. // Initialise this to nullptr; this will be set in Rml::CreateContext().
  53. render_interface = nullptr;
  54. root = Factory::InstanceElement(nullptr, "*", "#root", XMLAttributes());
  55. root->SetId(name);
  56. root->SetOffset(Vector2f(0, 0), nullptr);
  57. root->SetProperty(PropertyId::ZIndex, Property(0, Property::NUMBER));
  58. cursor_proxy = Factory::InstanceElement(nullptr, documents_base_tag, documents_base_tag, XMLAttributes());
  59. ElementDocument* cursor_proxy_document = rmlui_dynamic_cast< ElementDocument* >(cursor_proxy.get());
  60. RMLUI_ASSERT(cursor_proxy_document);
  61. cursor_proxy_document->context = this;
  62. // The cursor proxy takes the style from its cloned element's document. The latter may define style rules for `<body>` which we don't want on the
  63. // proxy. Thus, we override some properties here that we in particular don't want to inherit from the client document, especially those that
  64. // result in decoration of the body element.
  65. cursor_proxy_document->SetProperty(PropertyId::BackgroundColor, Property(Colourb(255, 255, 255, 0), Property::COLOUR));
  66. cursor_proxy_document->SetProperty(PropertyId::BorderTopWidth, Property(0, Property::PX));
  67. cursor_proxy_document->SetProperty(PropertyId::BorderRightWidth, Property(0, Property::PX));
  68. cursor_proxy_document->SetProperty(PropertyId::BorderBottomWidth, Property(0, Property::PX));
  69. cursor_proxy_document->SetProperty(PropertyId::BorderLeftWidth, Property(0, Property::PX));
  70. cursor_proxy_document->SetProperty(PropertyId::Decorator, Property());
  71. cursor_proxy_document->SetProperty(PropertyId::OverflowX, Property(Style::Overflow::Visible));
  72. cursor_proxy_document->SetProperty(PropertyId::OverflowY, Property(Style::Overflow::Visible));
  73. enable_cursor = true;
  74. document_focus_history.push_back(root.get());
  75. focus = root.get();
  76. hover = nullptr;
  77. active = nullptr;
  78. drag = nullptr;
  79. drag_started = false;
  80. drag_verbose = false;
  81. drag_clone = nullptr;
  82. drag_hover = nullptr;
  83. last_click_element = nullptr;
  84. last_click_time = 0;
  85. last_click_mouse_position = Vector2i(0, 0);
  86. }
  87. Context::~Context()
  88. {
  89. PluginRegistry::NotifyContextDestroy(this);
  90. UnloadAllDocuments();
  91. ReleaseUnloadedDocuments();
  92. root.reset();
  93. cursor_proxy.reset();
  94. instancer = nullptr;
  95. render_interface = nullptr;
  96. }
  97. // Returns the name of the context.
  98. const String& Context::GetName() const
  99. {
  100. return name;
  101. }
  102. // Changes the dimensions of the screen.
  103. void Context::SetDimensions(const Vector2i _dimensions)
  104. {
  105. if (dimensions != _dimensions)
  106. {
  107. dimensions = _dimensions;
  108. root->SetBox(Box(Vector2f(dimensions)));
  109. root->DirtyLayout();
  110. for (int i = 0; i < root->GetNumChildren(); ++i)
  111. {
  112. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  113. if (document != nullptr)
  114. {
  115. document->DirtyMediaQueries();
  116. document->DirtyVwAndVhProperties();
  117. document->DirtyLayout();
  118. document->DirtyPosition();
  119. document->DispatchEvent(EventId::Resize, Dictionary());
  120. }
  121. }
  122. clip_dimensions = dimensions;
  123. }
  124. }
  125. // Returns the dimensions of the screen.
  126. Vector2i Context::GetDimensions() const
  127. {
  128. return dimensions;
  129. }
  130. void Context::SetDensityIndependentPixelRatio(float _density_independent_pixel_ratio)
  131. {
  132. if (density_independent_pixel_ratio != _density_independent_pixel_ratio)
  133. {
  134. density_independent_pixel_ratio = _density_independent_pixel_ratio;
  135. for (int i = 0; i < root->GetNumChildren(true); ++i)
  136. {
  137. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  138. if (document)
  139. {
  140. document->DirtyMediaQueries();
  141. document->OnDpRatioChangeRecursive();
  142. }
  143. }
  144. }
  145. }
  146. float Context::GetDensityIndependentPixelRatio() const
  147. {
  148. return density_independent_pixel_ratio;
  149. }
  150. // Updates all elements in the element tree.
  151. bool Context::Update()
  152. {
  153. RMLUI_ZoneScoped;
  154. // Update all data models first
  155. for (auto& data_model : data_models)
  156. data_model.second->Update(true);
  157. root->Update(density_independent_pixel_ratio, Vector2f(dimensions));
  158. for (int i = 0; i < root->GetNumChildren(); ++i)
  159. if (auto doc = root->GetChild(i)->GetOwnerDocument())
  160. {
  161. doc->UpdateLayout();
  162. doc->UpdatePosition();
  163. }
  164. // Release any documents that were unloaded during the update.
  165. ReleaseUnloadedDocuments();
  166. return true;
  167. }
  168. // Renders all visible elements in the element tree.
  169. bool Context::Render()
  170. {
  171. RMLUI_ZoneScoped;
  172. RenderInterface* render_interface = GetRenderInterface();
  173. if (render_interface == nullptr)
  174. return false;
  175. render_interface->context = this;
  176. ElementUtilities::ApplyActiveClipRegion(this, render_interface);
  177. root->Render();
  178. ElementUtilities::SetClippingRegion(nullptr, this);
  179. // Render the cursor proxy so that any attached drag clone will be rendered below the cursor.
  180. if (drag_clone)
  181. {
  182. static_cast<ElementDocument&>(*cursor_proxy).UpdateDocument();
  183. cursor_proxy->SetOffset(Vector2f((float)Math::Clamp(mouse_position.x, 0, dimensions.x),
  184. (float)Math::Clamp(mouse_position.y, 0, dimensions.y)),
  185. nullptr);
  186. cursor_proxy->Render();
  187. }
  188. render_interface->context = nullptr;
  189. return true;
  190. }
  191. // Creates a new, empty document and places it into this context.
  192. ElementDocument* Context::CreateDocument(const String& instancer_name)
  193. {
  194. ElementPtr element = Factory::InstanceElement(nullptr, instancer_name, documents_base_tag, XMLAttributes());
  195. if (!element)
  196. {
  197. Log::Message(Log::LT_ERROR, "Failed to instance document on instancer_name '%s', instancer returned nullptr.", instancer_name.c_str());
  198. return nullptr;
  199. }
  200. ElementDocument* document = rmlui_dynamic_cast< ElementDocument* >(element.get());
  201. if (!document)
  202. {
  203. Log::Message(Log::LT_ERROR, "Failed to instance document on instancer_name '%s', Found type '%s', was expecting derivative of ElementDocument.", instancer_name.c_str(), rmlui_type_name(*element));
  204. return nullptr;
  205. }
  206. document->context = this;
  207. root->AppendChild(std::move(element));
  208. PluginRegistry::NotifyDocumentLoad(document);
  209. return document;
  210. }
  211. // Load a document into the context.
  212. ElementDocument* Context::LoadDocument(const String& document_path)
  213. {
  214. auto stream = MakeUnique<StreamFile>();
  215. if (!stream->Open(document_path))
  216. return nullptr;
  217. ElementDocument* document = LoadDocument(stream.get());
  218. return document;
  219. }
  220. // Load a document into the context.
  221. ElementDocument* Context::LoadDocument(Stream* stream)
  222. {
  223. PluginRegistry::NotifyDocumentOpen(this, stream->GetSourceURL().GetURL());
  224. ElementPtr element = Factory::InstanceDocumentStream(this, stream, GetDocumentsBaseTag());
  225. if (!element)
  226. return nullptr;
  227. ElementDocument* document = static_cast<ElementDocument*>(element.get());
  228. root->AppendChild(std::move(element));
  229. // The 'load' event is fired before updating the document, because the user might
  230. // need to initalize things before running an update. The drawback is that computed
  231. // values and layouting are not performed yet, resulting in default values when
  232. // querying such information in the event handler.
  233. PluginRegistry::NotifyDocumentLoad(document);
  234. document->DispatchEvent(EventId::Load, Dictionary());
  235. // Data models are updated after the 'load' event so that the user has a chance to change
  236. // any data variables first. We do not clear dirty variables here, since users may need to
  237. // retrieve whether or not eg. a data variable has changed in a controller.
  238. for (auto& data_model : data_models)
  239. data_model.second->Update(false);
  240. document->UpdateDocument();
  241. return document;
  242. }
  243. // Load a document into the context.
  244. ElementDocument* Context::LoadDocumentFromMemory(const String& string, const String& source_url)
  245. {
  246. // Open the stream based on the string contents.
  247. auto stream = MakeUnique<StreamMemory>((byte*)string.c_str(), string.size());
  248. stream->SetSourceURL( source_url );
  249. // Load the document from the stream.
  250. ElementDocument* document = LoadDocument(stream.get());
  251. return document;
  252. }
  253. // Unload the given document
  254. void Context::UnloadDocument(ElementDocument* _document)
  255. {
  256. // Has this document already been unloaded?
  257. for (size_t i = 0; i < unloaded_documents.size(); ++i)
  258. {
  259. if (unloaded_documents[i].get() == _document)
  260. return;
  261. }
  262. ElementDocument* document = _document;
  263. if (document->GetParentNode() == root.get())
  264. {
  265. // Dispatch the unload notifications.
  266. document->DispatchEvent(EventId::Unload, Dictionary());
  267. PluginRegistry::NotifyDocumentUnload(document);
  268. // Move document to a temporary location to be released later.
  269. unloaded_documents.push_back( root->RemoveChild(document) );
  270. }
  271. // Remove the item from the focus history.
  272. ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), document);
  273. if (itr != document_focus_history.end())
  274. document_focus_history.erase(itr);
  275. // Focus to the previous document if the old document is the current focus.
  276. if (focus && focus->GetOwnerDocument() == document)
  277. {
  278. focus = nullptr;
  279. document_focus_history.back()->GetFocusLeafNode()->Focus();
  280. }
  281. // Clear the active element if the old document is the active element.
  282. if (active && active->GetOwnerDocument() == document)
  283. {
  284. active = nullptr;
  285. }
  286. // Clear other pointers to elements whose owner was deleted
  287. if (drag && drag->GetOwnerDocument() == document)
  288. {
  289. drag = nullptr;
  290. ReleaseDragClone();
  291. }
  292. if (drag_hover && drag_hover->GetOwnerDocument() == document)
  293. {
  294. drag_hover = nullptr;
  295. }
  296. // Rebuild the hover state.
  297. UpdateHoverChain(Dictionary(), Dictionary(), mouse_position);
  298. }
  299. // Unload all the currently loaded documents
  300. void Context::UnloadAllDocuments()
  301. {
  302. // Unload all children.
  303. while (root->GetNumChildren(true) > 0)
  304. UnloadDocument(root->GetChild(0)->GetOwnerDocument());
  305. // The element lists may point to elements that are getting removed.
  306. active_chain.clear();
  307. hover_chain.clear();
  308. drag_hover_chain.clear();
  309. }
  310. // Enables or disables the mouse cursor.
  311. void Context::EnableMouseCursor(bool enable)
  312. {
  313. // The cursor is set to an invalid name so that it is forced to update in the next update loop.
  314. cursor_name = ":reset:";
  315. enable_cursor = enable;
  316. }
  317. void Context::ActivateTheme(const String& theme_name, bool activate)
  318. {
  319. bool theme_changed = false;
  320. if (activate)
  321. theme_changed = active_themes.insert(theme_name).second;
  322. else
  323. theme_changed = (active_themes.erase(theme_name) > 0);
  324. if (theme_changed)
  325. {
  326. for (int i = 0; i < root->GetNumChildren(true); ++i)
  327. {
  328. if (ElementDocument* document = root->GetChild(i)->GetOwnerDocument())
  329. document->DirtyMediaQueries();
  330. }
  331. }
  332. }
  333. bool Context::IsThemeActive(const String& theme_name) const
  334. {
  335. return active_themes.count(theme_name);
  336. }
  337. // Returns the first document found in the root with the given id.
  338. ElementDocument* Context::GetDocument(const String& id)
  339. {
  340. for (int i = 0; i < root->GetNumChildren(); i++)
  341. {
  342. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  343. if (document == nullptr)
  344. continue;
  345. if (document->GetId() == id)
  346. return document;
  347. }
  348. return nullptr;
  349. }
  350. // Returns a document in the context by index.
  351. ElementDocument* Context::GetDocument(int index)
  352. {
  353. Element* element = root->GetChild(index);
  354. if (element == nullptr)
  355. return nullptr;
  356. return element->GetOwnerDocument();
  357. }
  358. // Returns the number of documents in the context.
  359. int Context::GetNumDocuments() const
  360. {
  361. return root->GetNumChildren();
  362. }
  363. // Returns the hover element.
  364. Element* Context::GetHoverElement()
  365. {
  366. return hover;
  367. }
  368. // Returns the focus element.
  369. Element* Context::GetFocusElement()
  370. {
  371. return focus;
  372. }
  373. // Returns the root element.
  374. Element* Context::GetRootElement()
  375. {
  376. return root.get();
  377. }
  378. // Brings the document to the front of the document stack.
  379. void Context::PullDocumentToFront(ElementDocument* document)
  380. {
  381. if (document != root->GetLastChild())
  382. {
  383. // Calling RemoveChild() / AppendChild() would be cleaner, but that dirties the document's layout
  384. // unnecessarily, so we'll go under the hood here.
  385. for (int i = 0; i < root->GetNumChildren(); ++i)
  386. {
  387. if (root->GetChild(i) == document)
  388. {
  389. ElementPtr element = std::move(root->children[i]);
  390. root->children.erase(root->children.begin() + i);
  391. root->children.insert(root->children.begin() + root->GetNumChildren(), std::move(element));
  392. root->DirtyStackingContext();
  393. }
  394. }
  395. }
  396. }
  397. // Sends the document to the back of the document stack.
  398. void Context::PushDocumentToBack(ElementDocument* document)
  399. {
  400. if (document != root->GetFirstChild())
  401. {
  402. // See PullDocumentToFront().
  403. for (int i = 0; i < root->GetNumChildren(); ++i)
  404. {
  405. if (root->GetChild(i) == document)
  406. {
  407. ElementPtr element = std::move(root->children[i]);
  408. root->children.erase(root->children.begin() + i);
  409. root->children.insert(root->children.begin(), std::move(element));
  410. root->DirtyStackingContext();
  411. }
  412. }
  413. }
  414. }
  415. void Context::UnfocusDocument(ElementDocument* document)
  416. {
  417. auto it = std::find(document_focus_history.begin(), document_focus_history.end(), document);
  418. if (it != document_focus_history.end())
  419. document_focus_history.erase(it);
  420. if (!document_focus_history.empty())
  421. document_focus_history.back()->GetFocusLeafNode()->Focus();
  422. }
  423. // Adds an event listener to the root element.
  424. void Context::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  425. {
  426. root->AddEventListener(event, listener, in_capture_phase);
  427. }
  428. // Removes an event listener from the root element.
  429. void Context::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  430. {
  431. root->RemoveEventListener(event, listener, in_capture_phase);
  432. }
  433. // Sends a key down event into RmlUi.
  434. bool Context::ProcessKeyDown(Input::KeyIdentifier key_identifier, int key_modifier_state)
  435. {
  436. // Generate the parameters for the key event.
  437. Dictionary parameters;
  438. GenerateKeyEventParameters(parameters, key_identifier);
  439. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  440. if (focus)
  441. return focus->DispatchEvent(EventId::Keydown, parameters);
  442. else
  443. return root->DispatchEvent(EventId::Keydown, parameters);
  444. }
  445. // Sends a key up event into RmlUi.
  446. bool Context::ProcessKeyUp(Input::KeyIdentifier key_identifier, int key_modifier_state)
  447. {
  448. // Generate the parameters for the key event.
  449. Dictionary parameters;
  450. GenerateKeyEventParameters(parameters, key_identifier);
  451. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  452. if (focus)
  453. return focus->DispatchEvent(EventId::Keyup, parameters);
  454. else
  455. return root->DispatchEvent(EventId::Keyup, parameters);
  456. }
  457. bool Context::ProcessTextInput(char character)
  458. {
  459. // Only the standard ASCII character set is a valid subset of UTF-8.
  460. if (static_cast<unsigned char>(character) > 127)
  461. return false;
  462. return ProcessTextInput(static_cast<Character>(character));
  463. }
  464. // Sends a single character of text as text input into RmlUi.
  465. bool Context::ProcessTextInput(Character character)
  466. {
  467. // Generate the parameters for the key event.
  468. String text = StringUtilities::ToUTF8(character);
  469. return ProcessTextInput(text);
  470. }
  471. // Sends a string of text as text input into RmlUi.
  472. bool Context::ProcessTextInput(const String& string)
  473. {
  474. Element* target = (focus ? focus : root.get());
  475. Dictionary parameters;
  476. parameters["text"] = string;
  477. bool consumed = target->DispatchEvent(EventId::Textinput, parameters);
  478. return consumed;
  479. }
  480. // Sends a mouse movement event into RmlUi.
  481. bool Context::ProcessMouseMove(int x, int y, int key_modifier_state)
  482. {
  483. // Check whether the mouse moved since the last event came through.
  484. Vector2i old_mouse_position = mouse_position;
  485. bool mouse_moved = (x != mouse_position.x) || (y != mouse_position.y);
  486. if (mouse_moved)
  487. {
  488. mouse_position.x = x;
  489. mouse_position.y = y;
  490. }
  491. // Generate the parameters for the mouse events (there could be a few!).
  492. Dictionary parameters;
  493. GenerateMouseEventParameters(parameters, -1);
  494. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  495. Dictionary drag_parameters;
  496. GenerateMouseEventParameters(drag_parameters);
  497. GenerateDragEventParameters(drag_parameters);
  498. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  499. // Update the current hover chain. This will send all necessary 'onmouseout', 'onmouseover', 'ondragout' and
  500. // 'ondragover' messages.
  501. UpdateHoverChain(parameters, drag_parameters, old_mouse_position);
  502. // Dispatch any 'onmousemove' events.
  503. if (mouse_moved)
  504. {
  505. if (hover)
  506. {
  507. hover->DispatchEvent(EventId::Mousemove, parameters);
  508. if (drag_hover &&
  509. drag_verbose)
  510. drag_hover->DispatchEvent(EventId::Dragmove, drag_parameters);
  511. }
  512. }
  513. return !IsMouseInteracting();
  514. }
  515. static Element* FindFocusElement(Element* element)
  516. {
  517. ElementDocument* owner_document = element->GetOwnerDocument();
  518. if (!owner_document || owner_document->GetComputedValues().focus == Style::Focus::None)
  519. return nullptr;
  520. while (element && element->GetComputedValues().focus == Style::Focus::None)
  521. {
  522. element = element->GetParentNode();
  523. }
  524. return element;
  525. }
  526. // Sends a mouse-button down event into RmlUi.
  527. bool Context::ProcessMouseButtonDown(int button_index, int key_modifier_state)
  528. {
  529. Dictionary parameters;
  530. GenerateMouseEventParameters(parameters, button_index);
  531. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  532. if (button_index == 0)
  533. {
  534. Element* new_focus = hover;
  535. // Set the currently hovered element to focus if it isn't already the focus.
  536. if (hover)
  537. {
  538. new_focus = FindFocusElement(hover);
  539. if (new_focus && new_focus != focus)
  540. {
  541. if (!new_focus->Focus())
  542. return !IsMouseInteracting();
  543. }
  544. }
  545. // Save the just-pressed-on element as the pressed element.
  546. active = new_focus;
  547. bool propagate = true;
  548. // Call 'onmousedown' on every item in the hover chain, and copy the hover chain to the active chain.
  549. if (hover)
  550. propagate = hover->DispatchEvent(EventId::Mousedown, parameters);
  551. if (propagate)
  552. {
  553. // Check for a double-click on an element; if one has occured, we send the 'dblclick' event to the hover
  554. // element. If not, we'll start a timer to catch the next one.
  555. float mouse_distance_squared = float((mouse_position - last_click_mouse_position).SquaredMagnitude());
  556. float max_mouse_distance = DOUBLE_CLICK_MAX_DIST * density_independent_pixel_ratio;
  557. double click_time = GetSystemInterface()->GetElapsedTime();
  558. if (active == last_click_element &&
  559. float(click_time - last_click_time) < DOUBLE_CLICK_TIME &&
  560. mouse_distance_squared < max_mouse_distance * max_mouse_distance)
  561. {
  562. if (hover)
  563. propagate = hover->DispatchEvent(EventId::Dblclick, parameters);
  564. last_click_element = nullptr;
  565. last_click_time = 0;
  566. }
  567. else
  568. {
  569. last_click_element = active;
  570. last_click_time = click_time;
  571. }
  572. }
  573. last_click_mouse_position = mouse_position;
  574. active_chain.insert(active_chain.end(), hover_chain.begin(), hover_chain.end());
  575. if (propagate)
  576. {
  577. // Traverse down the hierarchy of the newly focused element (if any), and see if we can begin dragging it.
  578. drag_started = false;
  579. drag = hover;
  580. while (drag)
  581. {
  582. Style::Drag drag_style = drag->GetComputedValues().drag;
  583. switch (drag_style)
  584. {
  585. case Style::Drag::None: drag = drag->GetParentNode(); continue;
  586. case Style::Drag::Block: drag = nullptr; continue;
  587. default: drag_verbose = (drag_style == Style::Drag::DragDrop || drag_style == Style::Drag::Clone);
  588. }
  589. break;
  590. }
  591. }
  592. }
  593. else
  594. {
  595. // Not the primary mouse button, so we're not doing any special processing.
  596. if (hover)
  597. hover->DispatchEvent(EventId::Mousedown, parameters);
  598. }
  599. return !IsMouseInteracting();
  600. }
  601. // Sends a mouse-button up event into RmlUi.
  602. bool Context::ProcessMouseButtonUp(int button_index, int key_modifier_state)
  603. {
  604. Dictionary parameters;
  605. GenerateMouseEventParameters(parameters, button_index);
  606. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  607. // We want to return the interaction state before handling the mouse up events, so that any active element that is released is considered to capture the event.
  608. const bool result = !IsMouseInteracting();
  609. // Process primary click.
  610. if (button_index == 0)
  611. {
  612. // The elements in the new hover chain have the 'onmouseup' event called on them.
  613. if (hover)
  614. hover->DispatchEvent(EventId::Mouseup, parameters);
  615. // If the active element (the one that was being hovered over when the mouse button was pressed) is still being
  616. // hovered over, we click it.
  617. if (hover && active && active == FindFocusElement(hover))
  618. {
  619. active->DispatchEvent(EventId::Click, parameters);
  620. }
  621. // Unset the 'active' pseudo-class on all the elements in the active chain; because they may not necessarily
  622. // have had 'onmouseup' called on them, we can't guarantee this has happened already.
  623. std::for_each(active_chain.begin(), active_chain.end(), [](Element* element) {
  624. element->SetPseudoClass("active", false);
  625. });
  626. active_chain.clear();
  627. active = nullptr;
  628. if (drag)
  629. {
  630. if (drag_started)
  631. {
  632. Dictionary drag_parameters;
  633. GenerateMouseEventParameters(drag_parameters);
  634. GenerateDragEventParameters(drag_parameters);
  635. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  636. if (drag_hover)
  637. {
  638. if (drag_verbose)
  639. {
  640. drag_hover->DispatchEvent(EventId::Dragdrop, drag_parameters);
  641. // User may have removed the element, do an extra check.
  642. if(drag_hover)
  643. drag_hover->DispatchEvent(EventId::Dragout, drag_parameters);
  644. }
  645. }
  646. if(drag)
  647. drag->DispatchEvent(EventId::Dragend, drag_parameters);
  648. ReleaseDragClone();
  649. }
  650. drag = nullptr;
  651. drag_hover = nullptr;
  652. drag_hover_chain.clear();
  653. // We may have changes under our mouse, this ensures that the hover chain is properly updated
  654. ProcessMouseMove(mouse_position.x, mouse_position.y, key_modifier_state);
  655. }
  656. }
  657. else
  658. {
  659. // Not the left mouse button, so we're not doing any special processing.
  660. if (hover)
  661. hover->DispatchEvent(EventId::Mouseup, parameters);
  662. }
  663. return result;
  664. }
  665. // Sends a mouse-wheel movement event into RmlUi.
  666. bool Context::ProcessMouseWheel(float wheel_delta, int key_modifier_state)
  667. {
  668. if (hover)
  669. {
  670. Dictionary scroll_parameters;
  671. GenerateKeyModifierEventParameters(scroll_parameters, key_modifier_state);
  672. scroll_parameters["wheel_delta"] = wheel_delta;
  673. return hover->DispatchEvent(EventId::Mousescroll, scroll_parameters);
  674. }
  675. return true;
  676. }
  677. bool Context::IsMouseInteracting() const
  678. {
  679. return (hover && hover != root.get()) || (active && active != root.get());
  680. }
  681. // Gets the context's render interface.
  682. RenderInterface* Context::GetRenderInterface() const
  683. {
  684. return render_interface;
  685. }
  686. // Gets the current clipping region for the render traversal
  687. bool Context::GetActiveClipRegion(Vector2i& origin, Vector2i& dimensions) const
  688. {
  689. if (clip_dimensions.x < 0 || clip_dimensions.y < 0)
  690. return false;
  691. origin = clip_origin;
  692. dimensions = clip_dimensions;
  693. return true;
  694. }
  695. // Sets the current clipping region for the render traversal
  696. void Context::SetActiveClipRegion(const Vector2i origin, const Vector2i dimensions)
  697. {
  698. clip_origin = origin;
  699. clip_dimensions = dimensions;
  700. }
  701. // Sets the instancer to use for releasing this object.
  702. void Context::SetInstancer(ContextInstancer* _instancer)
  703. {
  704. RMLUI_ASSERT(instancer == nullptr);
  705. instancer = _instancer;
  706. }
  707. DataModelConstructor Context::CreateDataModel(const String& name)
  708. {
  709. if (!data_type_register)
  710. data_type_register = MakeUnique<DataTypeRegister>();
  711. auto result = data_models.emplace(name, MakeUnique<DataModel>(data_type_register->GetTransformFuncRegister()));
  712. bool inserted = result.second;
  713. if (inserted)
  714. return DataModelConstructor(result.first->second.get(), data_type_register.get());
  715. Log::Message(Log::LT_ERROR, "Data model name '%s' already exists.", name.c_str());
  716. return DataModelConstructor();
  717. }
  718. DataModelConstructor Context::GetDataModel(const String& name)
  719. {
  720. if (data_type_register)
  721. {
  722. if (DataModel* model = GetDataModelPtr(name))
  723. return DataModelConstructor(model, data_type_register.get());
  724. }
  725. Log::Message(Log::LT_ERROR, "Data model name '%s' could not be found.", name.c_str());
  726. return DataModelConstructor();
  727. }
  728. bool Context::RemoveDataModel(const String& name)
  729. {
  730. auto it = data_models.find(name);
  731. if (it == data_models.end())
  732. return false;
  733. DataModel* model = it->second.get();
  734. ElementList elements = model->GetAttachedModelRootElements();
  735. for (Element* element : elements)
  736. element->SetDataModel(nullptr);
  737. data_models.erase(it);
  738. return true;
  739. }
  740. // Internal callback for when an element is removed from the hierarchy.
  741. void Context::OnElementDetach(Element* element)
  742. {
  743. auto it_hover = hover_chain.find(element);
  744. if (it_hover != hover_chain.end())
  745. {
  746. Dictionary parameters;
  747. GenerateMouseEventParameters(parameters, -1);
  748. element->DispatchEvent(EventId::Mouseout, parameters);
  749. hover_chain.erase(it_hover);
  750. if (hover == element)
  751. hover = nullptr;
  752. }
  753. auto it_active = std::find(active_chain.begin(), active_chain.end(), element);
  754. if (it_active != active_chain.end())
  755. {
  756. active_chain.erase(it_active);
  757. if (active == element)
  758. active = nullptr;
  759. }
  760. if (drag)
  761. {
  762. auto it = drag_hover_chain.find(element);
  763. if (it != drag_hover_chain.end())
  764. {
  765. drag_hover_chain.erase(it);
  766. if (drag_hover == element)
  767. drag_hover = nullptr;
  768. }
  769. if (drag == element)
  770. {
  771. // The dragged element is being removed, silently cancel the drag operation
  772. if (drag_started)
  773. ReleaseDragClone();
  774. drag = nullptr;
  775. drag_hover = nullptr;
  776. drag_hover_chain.clear();
  777. }
  778. }
  779. // Focus normally cleared and set by parent during Element::RemoveChild.
  780. // However, there are some exceptions, such as when an there are multiple
  781. // ElementDocuments in the hierarchy above the current element.
  782. if (element == focus)
  783. focus = nullptr;
  784. // If the element is a document lower down in the hierarchy, we may need to remove it from the focus history.
  785. if (element->GetOwnerDocument() == element)
  786. {
  787. auto it = std::find(document_focus_history.begin(), document_focus_history.end(), element);
  788. if (it != document_focus_history.end())
  789. document_focus_history.erase(it);
  790. }
  791. }
  792. // Internal callback for when a new element gains focus
  793. bool Context::OnFocusChange(Element* new_focus)
  794. {
  795. RMLUI_ASSERT(new_focus);
  796. ElementSet old_chain;
  797. ElementSet new_chain;
  798. Element* old_focus = focus;
  799. ElementDocument* old_document = old_focus ? old_focus->GetOwnerDocument() : nullptr;
  800. ElementDocument* new_document = new_focus->GetOwnerDocument();
  801. // If the current focus is modal and the new focus is not modal, deny the request
  802. if (old_document && old_document->IsModal() && (!new_document || !new_document->GetOwnerDocument()->IsModal()))
  803. return false;
  804. // Build the old chains
  805. Element* element = old_focus;
  806. while (element)
  807. {
  808. old_chain.insert(element);
  809. element = element->GetParentNode();
  810. }
  811. // Build the new chain
  812. element = new_focus;
  813. while (element)
  814. {
  815. new_chain.insert(element);
  816. element = element->GetParentNode();
  817. }
  818. Dictionary parameters;
  819. // Send out blur/focus events.
  820. SendEvents(old_chain, new_chain, EventId::Blur, parameters);
  821. SendEvents(new_chain, old_chain, EventId::Focus, parameters);
  822. focus = new_focus;
  823. // Raise the element's document to the front, if desired.
  824. ElementDocument* document = focus->GetOwnerDocument();
  825. if (document != nullptr)
  826. {
  827. Style::ZIndex z_index_property = document->GetComputedValues().z_index;
  828. if (z_index_property.type == Style::ZIndex::Auto)
  829. document->PullToFront();
  830. }
  831. // Update the focus history
  832. if (old_document != new_document)
  833. {
  834. // If documents have changed, add the new document to the end of the history
  835. ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), new_document);
  836. if (itr != document_focus_history.end())
  837. document_focus_history.erase(itr);
  838. if (new_document != nullptr)
  839. document_focus_history.push_back(new_document);
  840. }
  841. return true;
  842. }
  843. // Generates an event for faking clicks on an element.
  844. void Context::GenerateClickEvent(Element* element)
  845. {
  846. Dictionary parameters;
  847. GenerateMouseEventParameters(parameters, 0);
  848. element->DispatchEvent(EventId::Click, parameters);
  849. }
  850. // Updates the current hover elements, sending required events.
  851. void Context::UpdateHoverChain(const Dictionary& parameters, const Dictionary& drag_parameters, const Vector2i old_mouse_position)
  852. {
  853. const Vector2f position(mouse_position);
  854. // Send out drag events.
  855. if (drag)
  856. {
  857. if (mouse_position != old_mouse_position)
  858. {
  859. if (!drag_started)
  860. {
  861. Dictionary drag_start_parameters = drag_parameters;
  862. drag_start_parameters["mouse_x"] = old_mouse_position.x;
  863. drag_start_parameters["mouse_y"] = old_mouse_position.y;
  864. drag->DispatchEvent(EventId::Dragstart, drag_start_parameters);
  865. drag_started = true;
  866. if (drag->GetComputedValues().drag == Style::Drag::Clone)
  867. {
  868. // Clone the element and attach it to the mouse cursor.
  869. CreateDragClone(drag);
  870. }
  871. }
  872. drag->DispatchEvent(EventId::Drag, drag_parameters);
  873. }
  874. }
  875. hover = GetElementAtPoint(position);
  876. if(enable_cursor)
  877. {
  878. String new_cursor_name;
  879. if(drag)
  880. new_cursor_name = drag->GetComputedValues().cursor;
  881. else if (hover)
  882. new_cursor_name = hover->GetComputedValues().cursor;
  883. if(new_cursor_name != cursor_name)
  884. {
  885. GetSystemInterface()->SetMouseCursor(new_cursor_name);
  886. cursor_name = new_cursor_name;
  887. }
  888. }
  889. // Build the new hover chain.
  890. ElementSet new_hover_chain;
  891. Element* element = hover;
  892. while (element != nullptr)
  893. {
  894. new_hover_chain.insert(element);
  895. element = element->GetParentNode();
  896. }
  897. // Send mouseout / mouseover events.
  898. SendEvents(hover_chain, new_hover_chain, EventId::Mouseout, parameters);
  899. SendEvents(new_hover_chain, hover_chain, EventId::Mouseover, parameters);
  900. // Send out drag events.
  901. if (drag)
  902. {
  903. drag_hover = GetElementAtPoint(position, drag);
  904. ElementSet new_drag_hover_chain;
  905. element = drag_hover;
  906. while (element != nullptr)
  907. {
  908. new_drag_hover_chain.insert(element);
  909. element = element->GetParentNode();
  910. }
  911. if (drag_started &&
  912. drag_verbose)
  913. {
  914. // Send out ondragover and ondragout events as appropriate.
  915. SendEvents(drag_hover_chain, new_drag_hover_chain, EventId::Dragout, drag_parameters);
  916. SendEvents(new_drag_hover_chain, drag_hover_chain, EventId::Dragover, drag_parameters);
  917. }
  918. drag_hover_chain.swap(new_drag_hover_chain);
  919. }
  920. // Swap the new chain in.
  921. hover_chain.swap(new_hover_chain);
  922. }
  923. // Returns the youngest descendent of the given element which is under the given point in screen coodinates.
  924. Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_element, Element* element) const
  925. {
  926. if (element == nullptr)
  927. {
  928. if (ignore_element == root.get())
  929. return nullptr;
  930. element = root.get();
  931. }
  932. // Check if any documents have modal focus; if so, only check down than document.
  933. if (element == root.get())
  934. {
  935. if (focus)
  936. {
  937. ElementDocument* focus_document = focus->GetOwnerDocument();
  938. if (focus_document != nullptr &&
  939. focus_document->IsModal())
  940. {
  941. element = focus_document;
  942. }
  943. }
  944. }
  945. // Check any elements within our stacking context. We want to return the lowest-down element
  946. // that is under the cursor.
  947. if (element->local_stacking_context)
  948. {
  949. if (element->stacking_context_dirty)
  950. element->BuildLocalStackingContext();
  951. for (int i = (int) element->stacking_context.size() - 1; i >= 0; --i)
  952. {
  953. if (ignore_element != nullptr)
  954. {
  955. Element* element_hierarchy = element->stacking_context[i];
  956. while (element_hierarchy != nullptr)
  957. {
  958. if (element_hierarchy == ignore_element)
  959. break;
  960. element_hierarchy = element_hierarchy->GetParentNode();
  961. }
  962. if (element_hierarchy != nullptr)
  963. continue;
  964. }
  965. Element* child_element = GetElementAtPoint(point, ignore_element, element->stacking_context[i]);
  966. if (child_element != nullptr)
  967. return child_element;
  968. }
  969. }
  970. // Ignore elements whose pointer events are disabled.
  971. if (element->GetComputedValues().pointer_events == Style::PointerEvents::None)
  972. return nullptr;
  973. // Projection may fail if we have a singular transformation matrix.
  974. bool projection_result = element->Project(point);
  975. // Check if the point is actually within this element.
  976. bool within_element = (projection_result && element->IsPointWithinElement(point));
  977. if (within_element)
  978. {
  979. Vector2i clip_origin, clip_dimensions;
  980. if (ElementUtilities::GetClippingRegion(clip_origin, clip_dimensions, element))
  981. {
  982. within_element = point.x >= clip_origin.x &&
  983. point.y >= clip_origin.y &&
  984. point.x <= (clip_origin.x + clip_dimensions.x) &&
  985. point.y <= (clip_origin.y + clip_dimensions.y);
  986. }
  987. }
  988. if (within_element)
  989. return element;
  990. return nullptr;
  991. }
  992. // Creates the drag clone from the given element.
  993. void Context::CreateDragClone(Element* element)
  994. {
  995. RMLUI_ASSERTMSG(cursor_proxy, "Unable to create drag clone, no cursor proxy document.");
  996. ReleaseDragClone();
  997. // Instance the drag clone.
  998. ElementPtr element_drag_clone = element->Clone();
  999. if (!element_drag_clone)
  1000. {
  1001. Log::Message(Log::LT_ERROR, "Unable to duplicate drag clone.");
  1002. return;
  1003. }
  1004. // Set the style sheet on the cursor proxy.
  1005. if (ElementDocument* document = element->GetOwnerDocument())
  1006. {
  1007. // Borrow the target document's style sheet. Sharing style sheet containers should be used with care, and
  1008. // only within the same context.
  1009. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheetContainer(document->style_sheet_container);
  1010. }
  1011. drag_clone = element_drag_clone.get();
  1012. // Append the clone to the cursor proxy element.
  1013. cursor_proxy->AppendChild(std::move(element_drag_clone));
  1014. // Set all the required properties and pseudo-classes on the clone.
  1015. drag_clone->SetPseudoClass("drag", true);
  1016. drag_clone->SetProperty(PropertyId::Position, Property(Style::Position::Absolute));
  1017. drag_clone->SetProperty(PropertyId::Left, Property(element->GetAbsoluteLeft() - element->GetBox().GetEdge(Box::MARGIN, Box::LEFT) - mouse_position.x, Property::PX));
  1018. drag_clone->SetProperty(PropertyId::Top, Property(element->GetAbsoluteTop() - element->GetBox().GetEdge(Box::MARGIN, Box::TOP) - mouse_position.y, Property::PX));
  1019. }
  1020. // Releases the drag clone, if one exists.
  1021. void Context::ReleaseDragClone()
  1022. {
  1023. if (drag_clone)
  1024. {
  1025. cursor_proxy->RemoveChild(drag_clone);
  1026. drag_clone = nullptr;
  1027. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheetContainer(nullptr);
  1028. }
  1029. }
  1030. DataModel* Context::GetDataModelPtr(const String& name) const
  1031. {
  1032. auto it = data_models.find(name);
  1033. if (it != data_models.end())
  1034. return it->second.get();
  1035. return nullptr;
  1036. }
  1037. // Builds the parameters for a generic key event.
  1038. void Context::GenerateKeyEventParameters(Dictionary& parameters, Input::KeyIdentifier key_identifier)
  1039. {
  1040. parameters["key_identifier"] = (int)key_identifier;
  1041. }
  1042. // Builds the parameters for a generic mouse event.
  1043. void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_index)
  1044. {
  1045. parameters.reserve(3);
  1046. parameters["mouse_x"] = mouse_position.x;
  1047. parameters["mouse_y"] = mouse_position.y;
  1048. if (button_index >= 0)
  1049. parameters["button"] = button_index;
  1050. }
  1051. // Builds the parameters for the key modifier state.
  1052. void Context::GenerateKeyModifierEventParameters(Dictionary& parameters, int key_modifier_state)
  1053. {
  1054. static const String property_names[] = {
  1055. "ctrl_key",
  1056. "shift_key",
  1057. "alt_key",
  1058. "meta_key",
  1059. "caps_lock_key",
  1060. "num_lock_key",
  1061. "scroll_lock_key"
  1062. };
  1063. for (int i = 0; i < 7; i++)
  1064. parameters[property_names[i]] = (int)((key_modifier_state & (1 << i)) > 0);
  1065. }
  1066. // Builds the parameters for a drag event.
  1067. void Context::GenerateDragEventParameters(Dictionary& parameters)
  1068. {
  1069. parameters["drag_element"] = (void*)drag;
  1070. }
  1071. // Releases all unloaded documents pending destruction.
  1072. void Context::ReleaseUnloadedDocuments()
  1073. {
  1074. if (!unloaded_documents.empty())
  1075. {
  1076. OwnedElementList documents = std::move(unloaded_documents);
  1077. unloaded_documents.clear();
  1078. // Clear the deleted list.
  1079. for (size_t i = 0; i < documents.size(); ++i)
  1080. documents[i]->GetEventDispatcher()->DetachAllEvents();
  1081. documents.clear();
  1082. }
  1083. }
  1084. using ElementObserverList = Vector< ObserverPtr<Element> >;
  1085. class ElementObserverListBackInserter {
  1086. public:
  1087. using iterator_category = std::output_iterator_tag;
  1088. using value_type = void;
  1089. using difference_type = void;
  1090. using pointer = void;
  1091. using reference = void;
  1092. using container_type = ElementObserverList;
  1093. ElementObserverListBackInserter(ElementObserverList& elements) : elements(&elements) {}
  1094. ElementObserverListBackInserter& operator=(Element* element) {
  1095. elements->push_back(element->GetObserverPtr());
  1096. return *this;
  1097. }
  1098. ElementObserverListBackInserter& operator*() { return *this; }
  1099. ElementObserverListBackInserter& operator++() { return *this; }
  1100. ElementObserverListBackInserter& operator++(int) { return *this; }
  1101. private:
  1102. ElementObserverList* elements;
  1103. };
  1104. // Sends the specified event to all elements in new_items that don't appear in old_items.
  1105. void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, EventId id, const Dictionary& parameters)
  1106. {
  1107. // We put our elements in observer pointers in case some of them are deleted during dispatch.
  1108. ElementObserverList elements;
  1109. std::set_difference(old_items.begin(), old_items.end(), new_items.begin(), new_items.end(), ElementObserverListBackInserter(elements));
  1110. for (auto& element : elements)
  1111. {
  1112. if (element)
  1113. element->DispatchEvent(id, parameters);
  1114. }
  1115. }
  1116. void Context::Release()
  1117. {
  1118. if (instancer)
  1119. {
  1120. instancer->ReleaseContext(this);
  1121. }
  1122. }
  1123. void Context::SetDocumentsBaseTag(const String& tag)
  1124. {
  1125. documents_base_tag = tag;
  1126. }
  1127. const String& Context::GetDocumentsBaseTag()
  1128. {
  1129. return documents_base_tag;
  1130. }
  1131. } // namespace Rml