Context.cpp 40 KB

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