Context.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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. // Position the clone. Use projected mouse coordinates to handle any ancestor transforms.
  1015. const Vector2f absolute_pos = element->GetAbsoluteOffset(Box::BORDER);
  1016. Vector2f projected_mouse_position = Vector2f(mouse_position);
  1017. if (Element* parent = element->GetParentNode())
  1018. parent->Project(projected_mouse_position);
  1019. drag_clone->SetProperty(PropertyId::Position, Property(Style::Position::Absolute));
  1020. drag_clone->SetProperty(PropertyId::Left, Property(absolute_pos.x - projected_mouse_position.x, Property::PX));
  1021. drag_clone->SetProperty(PropertyId::Top, Property(absolute_pos.y - projected_mouse_position.y, Property::PX));
  1022. // We remove margins so that percentage- and auto-margins are evaluated correctly.
  1023. drag_clone->SetProperty(PropertyId::MarginLeft, Property(0.f, Property::PX));
  1024. drag_clone->SetProperty(PropertyId::MarginTop, Property(0.f, Property::PX));
  1025. drag_clone->SetPseudoClass("drag", true);
  1026. }
  1027. // Releases the drag clone, if one exists.
  1028. void Context::ReleaseDragClone()
  1029. {
  1030. if (drag_clone)
  1031. {
  1032. cursor_proxy->RemoveChild(drag_clone);
  1033. drag_clone = nullptr;
  1034. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheetContainer(nullptr);
  1035. }
  1036. }
  1037. DataModel* Context::GetDataModelPtr(const String& name) const
  1038. {
  1039. auto it = data_models.find(name);
  1040. if (it != data_models.end())
  1041. return it->second.get();
  1042. return nullptr;
  1043. }
  1044. // Builds the parameters for a generic key event.
  1045. void Context::GenerateKeyEventParameters(Dictionary& parameters, Input::KeyIdentifier key_identifier)
  1046. {
  1047. parameters["key_identifier"] = (int)key_identifier;
  1048. }
  1049. // Builds the parameters for a generic mouse event.
  1050. void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_index)
  1051. {
  1052. parameters.reserve(3);
  1053. parameters["mouse_x"] = mouse_position.x;
  1054. parameters["mouse_y"] = mouse_position.y;
  1055. if (button_index >= 0)
  1056. parameters["button"] = button_index;
  1057. }
  1058. // Builds the parameters for the key modifier state.
  1059. void Context::GenerateKeyModifierEventParameters(Dictionary& parameters, int key_modifier_state)
  1060. {
  1061. static const String property_names[] = {
  1062. "ctrl_key",
  1063. "shift_key",
  1064. "alt_key",
  1065. "meta_key",
  1066. "caps_lock_key",
  1067. "num_lock_key",
  1068. "scroll_lock_key"
  1069. };
  1070. for (int i = 0; i < 7; i++)
  1071. parameters[property_names[i]] = (int)((key_modifier_state & (1 << i)) > 0);
  1072. }
  1073. // Builds the parameters for a drag event.
  1074. void Context::GenerateDragEventParameters(Dictionary& parameters)
  1075. {
  1076. parameters["drag_element"] = (void*)drag;
  1077. }
  1078. // Releases all unloaded documents pending destruction.
  1079. void Context::ReleaseUnloadedDocuments()
  1080. {
  1081. if (!unloaded_documents.empty())
  1082. {
  1083. OwnedElementList documents = std::move(unloaded_documents);
  1084. unloaded_documents.clear();
  1085. // Clear the deleted list.
  1086. for (size_t i = 0; i < documents.size(); ++i)
  1087. documents[i]->GetEventDispatcher()->DetachAllEvents();
  1088. documents.clear();
  1089. }
  1090. }
  1091. using ElementObserverList = Vector< ObserverPtr<Element> >;
  1092. class ElementObserverListBackInserter {
  1093. public:
  1094. using iterator_category = std::output_iterator_tag;
  1095. using value_type = void;
  1096. using difference_type = void;
  1097. using pointer = void;
  1098. using reference = void;
  1099. using container_type = ElementObserverList;
  1100. ElementObserverListBackInserter(ElementObserverList& elements) : elements(&elements) {}
  1101. ElementObserverListBackInserter& operator=(Element* element) {
  1102. elements->push_back(element->GetObserverPtr());
  1103. return *this;
  1104. }
  1105. ElementObserverListBackInserter& operator*() { return *this; }
  1106. ElementObserverListBackInserter& operator++() { return *this; }
  1107. ElementObserverListBackInserter& operator++(int) { return *this; }
  1108. private:
  1109. ElementObserverList* elements;
  1110. };
  1111. // Sends the specified event to all elements in new_items that don't appear in old_items.
  1112. void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, EventId id, const Dictionary& parameters)
  1113. {
  1114. // We put our elements in observer pointers in case some of them are deleted during dispatch.
  1115. ElementObserverList elements;
  1116. std::set_difference(old_items.begin(), old_items.end(), new_items.begin(), new_items.end(), ElementObserverListBackInserter(elements));
  1117. for (auto& element : elements)
  1118. {
  1119. if (element)
  1120. element->DispatchEvent(id, parameters);
  1121. }
  1122. }
  1123. void Context::Release()
  1124. {
  1125. if (instancer)
  1126. {
  1127. instancer->ReleaseContext(this);
  1128. }
  1129. }
  1130. void Context::SetDocumentsBaseTag(const String& tag)
  1131. {
  1132. documents_base_tag = tag;
  1133. }
  1134. const String& Context::GetDocumentsBaseTag()
  1135. {
  1136. return documents_base_tag;
  1137. }
  1138. } // namespace Rml