Context.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../../Include/RmlUi/Core/Context.h"
  29. #include "../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../Include/RmlUi/Core/ContextInstancer.h"
  31. #include "../../Include/RmlUi/Core/Core.h"
  32. #include "../../Include/RmlUi/Core/DataModelHandle.h"
  33. #include "../../Include/RmlUi/Core/Debug.h"
  34. #include "../../Include/RmlUi/Core/ElementDocument.h"
  35. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  36. #include "../../Include/RmlUi/Core/Factory.h"
  37. #include "../../Include/RmlUi/Core/Profiling.h"
  38. #include "../../Include/RmlUi/Core/RenderManager.h"
  39. #include "../../Include/RmlUi/Core/StreamMemory.h"
  40. #include "../../Include/RmlUi/Core/SystemInterface.h"
  41. #include "DataModel.h"
  42. #include "EventDispatcher.h"
  43. #include "PluginRegistry.h"
  44. #include "ScrollController.h"
  45. #include "StreamFile.h"
  46. #include <algorithm>
  47. #include <iterator>
  48. #include <limits>
  49. namespace Rml {
  50. static constexpr float DOUBLE_CLICK_TIME = 0.5f; // [s]
  51. static constexpr float DOUBLE_CLICK_MAX_DIST = 3.f; // [dp]
  52. static constexpr float UNIT_SCROLL_LENGTH = 80.f; // [dp]
  53. Context::Context(const String& name, RenderManager* render_manager, TextInputHandler* text_input_handler) :
  54. name(name), render_manager(render_manager), text_input_handler(text_input_handler)
  55. {
  56. instancer = nullptr;
  57. root = Factory::InstanceElement(nullptr, "*", "#root", XMLAttributes());
  58. root->SetId(name);
  59. root->SetOffset(Vector2f(0, 0), nullptr);
  60. root->SetProperty(PropertyId::ZIndex, Property(0, Unit::NUMBER));
  61. cursor_proxy = Factory::InstanceElement(nullptr, documents_base_tag, documents_base_tag, XMLAttributes());
  62. ElementDocument* cursor_proxy_document = rmlui_dynamic_cast<ElementDocument*>(cursor_proxy.get());
  63. RMLUI_ASSERT(cursor_proxy_document);
  64. cursor_proxy_document->context = this;
  65. // 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
  66. // proxy. Thus, we override some properties here that we in particular don't want to inherit from the client document, especially those that
  67. // result in decoration of the body element.
  68. cursor_proxy_document->SetProperty(PropertyId::BackgroundColor, Property(Colourb(255, 255, 255, 0), Unit::COLOUR));
  69. cursor_proxy_document->SetProperty(PropertyId::BorderTopWidth, Property(0, Unit::PX));
  70. cursor_proxy_document->SetProperty(PropertyId::BorderRightWidth, Property(0, Unit::PX));
  71. cursor_proxy_document->SetProperty(PropertyId::BorderBottomWidth, Property(0, Unit::PX));
  72. cursor_proxy_document->SetProperty(PropertyId::BorderLeftWidth, Property(0, Unit::PX));
  73. cursor_proxy_document->SetProperty(PropertyId::Decorator, Property());
  74. cursor_proxy_document->SetProperty(PropertyId::OverflowX, Property(Style::Overflow::Visible));
  75. cursor_proxy_document->SetProperty(PropertyId::OverflowY, Property(Style::Overflow::Visible));
  76. document_focus_history.push_back(root.get());
  77. focus = root.get();
  78. hover = nullptr;
  79. active = nullptr;
  80. drag = nullptr;
  81. drag_started = false;
  82. drag_verbose = false;
  83. drag_clone = nullptr;
  84. drag_hover = nullptr;
  85. last_click_element = nullptr;
  86. last_click_time = 0;
  87. mouse_active = false;
  88. enable_cursor = true;
  89. scroll_controller = MakeUnique<ScrollController>();
  90. }
  91. Context::~Context()
  92. {
  93. PluginRegistry::NotifyContextDestroy(this);
  94. UnloadAllDocuments();
  95. ReleaseUnloadedDocuments();
  96. root.reset();
  97. cursor_proxy.reset();
  98. instancer = nullptr;
  99. }
  100. const String& Context::GetName() const
  101. {
  102. return name;
  103. }
  104. void Context::SetDimensions(const Vector2i _dimensions)
  105. {
  106. if (dimensions != _dimensions)
  107. {
  108. dimensions = _dimensions;
  109. render_manager->SetViewport(dimensions);
  110. root->SetBox(Box(Vector2f(dimensions)));
  111. root->DirtyLayout();
  112. for (int i = 0; i < root->GetNumChildren(); ++i)
  113. {
  114. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  115. if (document != nullptr)
  116. {
  117. document->DirtyMediaQueries();
  118. document->DirtyVwAndVhProperties();
  119. document->DirtyLayout();
  120. document->DirtyPosition();
  121. document->DispatchEvent(EventId::Resize, Dictionary());
  122. }
  123. }
  124. }
  125. }
  126. Vector2i Context::GetDimensions() const
  127. {
  128. return dimensions;
  129. }
  130. void Context::SetDensityIndependentPixelRatio(float dp_ratio)
  131. {
  132. if (density_independent_pixel_ratio != dp_ratio)
  133. {
  134. density_independent_pixel_ratio = dp_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. bool Context::Update()
  151. {
  152. RMLUI_ZoneScoped;
  153. next_update_timeout = std::numeric_limits<double>::infinity();
  154. if (scroll_controller->Update(mouse_position, density_independent_pixel_ratio))
  155. RequestNextUpdate(0);
  156. // Update the hover chain to detect any new or moved elements under the mouse.
  157. if (mouse_active)
  158. UpdateHoverChain(mouse_position);
  159. // Update all the data models before updating properties and layout.
  160. for (auto& data_model : data_models)
  161. data_model.second->Update(true);
  162. // The style definition of each document should be independent of each other. By manually resetting these flags we avoid unnecessary definition
  163. // lookups in unrelated documents, such as when adding a new document. Adding an element dirties the parent definition, which in this case is the
  164. // root. By extension the definition of all the other documents are also dirtied, unnecessarily.
  165. root->dirty_definition = false;
  166. root->dirty_child_definitions = false;
  167. root->Update(density_independent_pixel_ratio, Vector2f(dimensions));
  168. for (int i = 0; i < root->GetNumChildren(); ++i)
  169. {
  170. if (auto doc = root->GetChild(i)->GetOwnerDocument())
  171. {
  172. doc->UpdateLayout();
  173. doc->UpdatePosition();
  174. }
  175. }
  176. // Release any documents that were unloaded during the update.
  177. ReleaseUnloadedDocuments();
  178. return true;
  179. }
  180. bool Context::Render()
  181. {
  182. RMLUI_ZoneScoped;
  183. render_manager->PrepareRender(dimensions);
  184. root->Render();
  185. // Render the cursor proxy so that any attached drag clone will be rendered below the cursor.
  186. if (drag_clone)
  187. {
  188. static_cast<ElementDocument&>(*cursor_proxy).UpdateDocument();
  189. cursor_proxy->SetOffset(
  190. Vector2f((float)Math::Clamp(mouse_position.x, 0, dimensions.x), (float)Math::Clamp(mouse_position.y, 0, dimensions.y)), nullptr);
  191. cursor_proxy->Render();
  192. }
  193. render_manager->ResetState();
  194. return true;
  195. }
  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,
  208. "Failed to instance document on instancer_name '%s', Found type '%s', was expecting derivative of ElementDocument.",
  209. instancer_name.c_str(), rmlui_type_name(*element));
  210. return nullptr;
  211. }
  212. document->context = this;
  213. root->AppendChild(std::move(element));
  214. PluginRegistry::NotifyDocumentLoad(document);
  215. return document;
  216. }
  217. ElementDocument* Context::LoadDocument(const String& document_path)
  218. {
  219. auto stream = MakeUnique<StreamFile>();
  220. if (!stream->Open(document_path))
  221. return nullptr;
  222. ElementDocument* document = LoadDocument(stream.get());
  223. return document;
  224. }
  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 = rmlui_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. ElementDocument* Context::LoadDocumentFromMemory(const String& string, const String& source_url)
  248. {
  249. // Open the stream based on the string contents.
  250. auto stream = MakeUnique<StreamMemory>(reinterpret_cast<const byte*>(string.c_str()), string.size());
  251. stream->SetSourceURL(source_url);
  252. // Load the document from the stream.
  253. ElementDocument* document = LoadDocument(stream.get());
  254. return document;
  255. }
  256. void Context::UnloadDocument(ElementDocument* _document)
  257. {
  258. // Has this document already been unloaded?
  259. for (size_t i = 0; i < unloaded_documents.size(); ++i)
  260. {
  261. if (unloaded_documents[i].get() == _document)
  262. return;
  263. }
  264. ElementDocument* document = _document;
  265. if (document->GetParentNode() == root.get())
  266. {
  267. // Dispatch the unload notifications.
  268. document->DispatchEvent(EventId::Unload, Dictionary());
  269. PluginRegistry::NotifyDocumentUnload(document);
  270. // Move document to a temporary location to be released later.
  271. unloaded_documents.push_back(root->RemoveChild(document));
  272. }
  273. // Remove the item from the focus history.
  274. ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), document);
  275. if (itr != document_focus_history.end())
  276. document_focus_history.erase(itr);
  277. // Focus to the previous document if the old document is the current focus.
  278. if (focus && focus->GetOwnerDocument() == document)
  279. {
  280. focus = nullptr;
  281. document_focus_history.back()->GetFocusLeafNode()->Focus();
  282. }
  283. // Clear the active element if the old document is the active element.
  284. if (active && active->GetOwnerDocument() == document)
  285. {
  286. active = nullptr;
  287. }
  288. // Clear other pointers to elements whose owner was deleted
  289. if (drag && drag->GetOwnerDocument() == document)
  290. {
  291. drag = nullptr;
  292. ReleaseDragClone();
  293. }
  294. if (drag_hover && drag_hover->GetOwnerDocument() == document)
  295. {
  296. drag_hover = nullptr;
  297. }
  298. // Rebuild the hover state.
  299. UpdateHoverChain(mouse_position);
  300. }
  301. void Context::UnloadAllDocuments()
  302. {
  303. // Unload all children.
  304. while (root->GetNumChildren(true) > 0)
  305. UnloadDocument(root->GetChild(0)->GetOwnerDocument());
  306. // The element lists may point to elements that are getting removed.
  307. active_chain.clear();
  308. hover_chain.clear();
  309. drag_hover_chain.clear();
  310. }
  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. ElementDocument* Context::GetDocument(const String& id)
  338. {
  339. for (int i = 0; i < root->GetNumChildren(); i++)
  340. {
  341. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  342. if (document == nullptr)
  343. continue;
  344. if (document->GetId() == id)
  345. return document;
  346. }
  347. return nullptr;
  348. }
  349. ElementDocument* Context::GetDocument(int index)
  350. {
  351. Element* element = root->GetChild(index);
  352. if (element == nullptr)
  353. return nullptr;
  354. return element->GetOwnerDocument();
  355. }
  356. int Context::GetNumDocuments() const
  357. {
  358. return root->GetNumChildren();
  359. }
  360. Element* Context::GetHoverElement()
  361. {
  362. return hover;
  363. }
  364. Element* Context::GetFocusElement()
  365. {
  366. return focus;
  367. }
  368. Element* Context::GetRootElement()
  369. {
  370. return root.get();
  371. }
  372. void Context::PullDocumentToFront(ElementDocument* document)
  373. {
  374. if (document != root->GetLastChild())
  375. {
  376. // Calling RemoveChild() / AppendChild() would be cleaner, but that dirties the document's layout
  377. // unnecessarily, so we'll go under the hood here.
  378. for (int i = 0; i < root->GetNumChildren(); ++i)
  379. {
  380. if (root->GetChild(i) == document)
  381. {
  382. ElementPtr element = std::move(root->children[i]);
  383. root->children.erase(root->children.begin() + i);
  384. root->children.insert(root->children.begin() + root->GetNumChildren(), std::move(element));
  385. root->DirtyStackingContext();
  386. }
  387. }
  388. }
  389. }
  390. void Context::PushDocumentToBack(ElementDocument* document)
  391. {
  392. if (document != root->GetFirstChild())
  393. {
  394. // See PullDocumentToFront().
  395. for (int i = 0; i < root->GetNumChildren(); ++i)
  396. {
  397. if (root->GetChild(i) == document)
  398. {
  399. ElementPtr element = std::move(root->children[i]);
  400. root->children.erase(root->children.begin() + i);
  401. root->children.insert(root->children.begin(), std::move(element));
  402. root->DirtyStackingContext();
  403. }
  404. }
  405. }
  406. }
  407. void Context::UnfocusDocument(ElementDocument* document)
  408. {
  409. auto it = std::find(document_focus_history.begin(), document_focus_history.end(), document);
  410. if (it != document_focus_history.end())
  411. document_focus_history.erase(it);
  412. if (!document_focus_history.empty())
  413. document_focus_history.back()->GetFocusLeafNode()->Focus();
  414. }
  415. void Context::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  416. {
  417. root->AddEventListener(event, listener, in_capture_phase);
  418. }
  419. void Context::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  420. {
  421. root->RemoveEventListener(event, listener, in_capture_phase);
  422. }
  423. bool Context::ProcessKeyDown(Input::KeyIdentifier key_identifier, int key_modifier_state)
  424. {
  425. // Generate the parameters for the key event.
  426. Dictionary parameters;
  427. GenerateKeyEventParameters(parameters, key_identifier);
  428. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  429. if (focus)
  430. return focus->DispatchEvent(EventId::Keydown, parameters);
  431. else
  432. return root->DispatchEvent(EventId::Keydown, parameters);
  433. }
  434. bool Context::ProcessKeyUp(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::Keyup, parameters);
  442. else
  443. return root->DispatchEvent(EventId::Keyup, parameters);
  444. }
  445. bool Context::ProcessTextInput(char character)
  446. {
  447. // Only the standard ASCII character set is a valid subset of UTF-8.
  448. if (static_cast<unsigned char>(character) > 127)
  449. return false;
  450. return ProcessTextInput(static_cast<Character>(character));
  451. }
  452. bool Context::ProcessTextInput(Character character)
  453. {
  454. // Generate the parameters for the key event.
  455. String text = StringUtilities::ToUTF8(character);
  456. return ProcessTextInput(text);
  457. }
  458. bool Context::ProcessTextInput(const String& string)
  459. {
  460. Element* target = (focus ? focus : root.get());
  461. Dictionary parameters;
  462. parameters["text"] = string;
  463. bool consumed = target->DispatchEvent(EventId::Textinput, parameters);
  464. return consumed;
  465. }
  466. bool Context::ProcessMouseMove(int x, int y, int key_modifier_state)
  467. {
  468. // Check whether the mouse moved since the last event came through.
  469. Vector2i old_mouse_position = mouse_position;
  470. mouse_position = {x, y};
  471. const bool mouse_moved = (mouse_position != old_mouse_position || !mouse_active);
  472. mouse_active = true;
  473. // Update the current hover chain. This will send all necessary 'onmouseout', 'onmouseover', 'ondragout' and 'ondragover' messages.
  474. Dictionary parameters, drag_parameters;
  475. UpdateHoverChain(old_mouse_position, key_modifier_state, &parameters, &drag_parameters);
  476. // Dispatch any 'onmousemove' events.
  477. if (mouse_moved)
  478. {
  479. if (hover)
  480. {
  481. hover->DispatchEvent(EventId::Mousemove, parameters);
  482. if (drag_hover && drag_verbose)
  483. drag_hover->DispatchEvent(EventId::Dragmove, drag_parameters);
  484. }
  485. }
  486. return !IsMouseInteracting();
  487. }
  488. static Element* FindFocusElement(Element* element)
  489. {
  490. ElementDocument* owner_document = element->GetOwnerDocument();
  491. if (!owner_document || owner_document->GetComputedValues().focus() == Style::Focus::None)
  492. return nullptr;
  493. while (element && element->GetComputedValues().focus() == Style::Focus::None)
  494. {
  495. element = element->GetParentNode();
  496. }
  497. return element;
  498. }
  499. bool Context::ProcessMouseButtonDown(int button_index, int key_modifier_state)
  500. {
  501. Dictionary parameters;
  502. GenerateMouseEventParameters(parameters, button_index);
  503. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  504. bool propagate = true;
  505. if (button_index == 0)
  506. {
  507. Element* new_focus = hover;
  508. // Set the currently hovered element to focus if it isn't already the focus.
  509. if (hover)
  510. {
  511. new_focus = FindFocusElement(hover);
  512. if (new_focus && new_focus != focus)
  513. {
  514. if (!new_focus->Focus())
  515. return !IsMouseInteracting();
  516. }
  517. }
  518. // Save the just-pressed-on element as the pressed element.
  519. active = new_focus;
  520. // Call 'onmousedown' on every item in the hover chain, and copy the hover chain to the active chain.
  521. if (hover)
  522. propagate = hover->DispatchEvent(EventId::Mousedown, parameters);
  523. if (propagate)
  524. {
  525. // Check for a double-click on an element; if one has occured, we send the 'dblclick' event to the hover
  526. // element. If not, we'll start a timer to catch the next one.
  527. float mouse_distance_squared = float((mouse_position - last_click_mouse_position).SquaredMagnitude());
  528. float max_mouse_distance = DOUBLE_CLICK_MAX_DIST * density_independent_pixel_ratio;
  529. double click_time = GetSystemInterface()->GetElapsedTime();
  530. if (active == last_click_element && float(click_time - last_click_time) < DOUBLE_CLICK_TIME &&
  531. mouse_distance_squared < max_mouse_distance * max_mouse_distance)
  532. {
  533. if (hover)
  534. propagate = hover->DispatchEvent(EventId::Dblclick, parameters);
  535. last_click_element = nullptr;
  536. last_click_time = 0;
  537. }
  538. else
  539. {
  540. last_click_element = active;
  541. last_click_time = click_time;
  542. }
  543. }
  544. last_click_mouse_position = mouse_position;
  545. active_chain.insert(active_chain.end(), hover_chain.begin(), hover_chain.end());
  546. if (propagate)
  547. {
  548. // Traverse down the hierarchy of the newly focused element (if any), and see if we can begin dragging it.
  549. drag_started = false;
  550. drag = hover;
  551. while (drag)
  552. {
  553. Style::Drag drag_style = drag->GetComputedValues().drag();
  554. switch (drag_style)
  555. {
  556. case Style::Drag::None: drag = drag->GetParentNode(); continue;
  557. case Style::Drag::Block: drag = nullptr; continue;
  558. default: drag_verbose = (drag_style == Style::Drag::DragDrop || drag_style == Style::Drag::Clone);
  559. }
  560. break;
  561. }
  562. }
  563. }
  564. else
  565. {
  566. // Not the primary mouse button, so we're not doing any special processing.
  567. if (hover)
  568. propagate = hover->DispatchEvent(EventId::Mousedown, parameters);
  569. }
  570. if (scroll_controller->GetMode() == ScrollController::Mode::Autoscroll)
  571. {
  572. scroll_controller->Reset();
  573. }
  574. else if (button_index == 2 && hover && propagate)
  575. {
  576. Dictionary scroll_parameters;
  577. GenerateMouseEventParameters(scroll_parameters);
  578. GenerateKeyModifierEventParameters(scroll_parameters, key_modifier_state);
  579. scroll_parameters["autoscroll"] = true;
  580. // Dispatch a mouse scroll event, this gives elements an opportunity to block autoscroll from being initialized.
  581. if (hover->DispatchEvent(EventId::Mousescroll, scroll_parameters))
  582. scroll_controller->ActivateAutoscroll(hover->GetClosestScrollableContainer(), mouse_position);
  583. }
  584. return !IsMouseInteracting();
  585. }
  586. bool Context::ProcessMouseButtonUp(int button_index, int key_modifier_state)
  587. {
  588. Dictionary parameters;
  589. GenerateMouseEventParameters(parameters, button_index);
  590. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  591. // We want to return the interaction state before handling the mouse up events, so that any active element that is released is considered to
  592. // capture the event.
  593. const bool result = !IsMouseInteracting();
  594. // Process primary click.
  595. if (button_index == 0)
  596. {
  597. // The elements in the new hover chain have the 'onmouseup' event called on them.
  598. if (hover)
  599. hover->DispatchEvent(EventId::Mouseup, parameters);
  600. // If the active element (the one that was being hovered over when the mouse button was pressed) is still being
  601. // hovered over, we click it.
  602. if (hover && active && active == FindFocusElement(hover))
  603. {
  604. active->DispatchEvent(EventId::Click, parameters);
  605. }
  606. // Unset the 'active' pseudo-class on all the elements in the active chain; because they may not necessarily
  607. // have had 'onmouseup' called on them, we can't guarantee this has happened already.
  608. for (Element* element : active_chain)
  609. element->SetPseudoClass("active", false);
  610. active_chain.clear();
  611. active = nullptr;
  612. if (drag)
  613. {
  614. if (drag_started)
  615. {
  616. Dictionary drag_parameters;
  617. GenerateMouseEventParameters(drag_parameters);
  618. GenerateDragEventParameters(drag_parameters);
  619. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  620. if (drag_hover)
  621. {
  622. if (drag_verbose)
  623. {
  624. drag_hover->DispatchEvent(EventId::Dragdrop, drag_parameters);
  625. // User may have removed the element, do an extra check.
  626. if (drag_hover)
  627. drag_hover->DispatchEvent(EventId::Dragout, drag_parameters);
  628. }
  629. }
  630. if (drag)
  631. drag->DispatchEvent(EventId::Dragend, drag_parameters);
  632. ReleaseDragClone();
  633. }
  634. drag = nullptr;
  635. drag_hover = nullptr;
  636. drag_hover_chain.clear();
  637. // We may have changes under our mouse, this ensures that the hover chain is properly updated
  638. ProcessMouseMove(mouse_position.x, mouse_position.y, key_modifier_state);
  639. }
  640. }
  641. else
  642. {
  643. // Not the left mouse button, so we're not doing any special processing.
  644. if (hover)
  645. hover->DispatchEvent(EventId::Mouseup, parameters);
  646. }
  647. // If we have autoscrolled while holding the middle mouse button, release the autoscroll mode now.
  648. if (scroll_controller->HasAutoscrollMoved())
  649. scroll_controller->Reset();
  650. return result;
  651. }
  652. bool Context::ProcessMouseWheel(float wheel_delta, int key_modifier_state)
  653. {
  654. return ProcessMouseWheel(Vector2f{0.f, wheel_delta}, key_modifier_state);
  655. }
  656. bool Context::ProcessMouseWheel(Vector2f wheel_delta, int key_modifier_state)
  657. {
  658. if (scroll_controller->GetMode() == ScrollController::Mode::Autoscroll)
  659. {
  660. scroll_controller->Reset();
  661. return false;
  662. }
  663. else if (!hover)
  664. {
  665. scroll_controller->Reset();
  666. return true;
  667. }
  668. Dictionary scroll_parameters;
  669. GenerateMouseEventParameters(scroll_parameters);
  670. GenerateKeyModifierEventParameters(scroll_parameters, key_modifier_state);
  671. scroll_parameters["wheel_delta_x"] = wheel_delta.x;
  672. scroll_parameters["wheel_delta_y"] = wheel_delta.y;
  673. // Dispatch a mouse scroll event, this gives elements an opportunity to block scrolling from being performed.
  674. if (!hover->DispatchEvent(EventId::Mousescroll, scroll_parameters))
  675. return false;
  676. const float unit_scroll_length = UNIT_SCROLL_LENGTH * density_independent_pixel_ratio;
  677. const Vector2f scroll_length = wheel_delta * unit_scroll_length;
  678. Element* target = hover->GetClosestScrollableContainer();
  679. if (scroll_controller->GetMode() == ScrollController::Mode::Smoothscroll && scroll_controller->GetTarget() == target)
  680. scroll_controller->IncrementSmoothscrollTarget(scroll_length);
  681. else
  682. scroll_controller->ActivateSmoothscroll(target, scroll_length, ScrollBehavior::Auto);
  683. return target == nullptr;
  684. }
  685. bool Context::ProcessMouseLeave()
  686. {
  687. mouse_active = false;
  688. // Update the hover chain. Now that 'mouse_active' is disabled this will remove the hover state from all elements.
  689. UpdateHoverChain(mouse_position);
  690. return !IsMouseInteracting();
  691. }
  692. bool Context::IsMouseInteracting() const
  693. {
  694. return (hover && hover != root.get()) || (active && active != root.get()) || scroll_controller->GetMode() == ScrollController::Mode::Autoscroll;
  695. }
  696. void Context::SetDefaultScrollBehavior(ScrollBehavior scroll_behavior, float speed_factor)
  697. {
  698. scroll_controller->SetDefaultScrollBehavior(scroll_behavior, speed_factor);
  699. }
  700. RenderManager& Context::GetRenderManager()
  701. {
  702. return *render_manager;
  703. }
  704. TextInputHandler* Context::GetTextInputHandler() const
  705. {
  706. return text_input_handler;
  707. }
  708. void Context::SetInstancer(ContextInstancer* _instancer)
  709. {
  710. RMLUI_ASSERT(instancer == nullptr);
  711. instancer = _instancer;
  712. }
  713. DataModelConstructor Context::CreateDataModel(const String& name, DataTypeRegister* data_type_register)
  714. {
  715. if (!data_type_register)
  716. {
  717. if (!default_data_type_register)
  718. default_data_type_register = MakeUnique<DataTypeRegister>();
  719. data_type_register = default_data_type_register.get();
  720. }
  721. auto result = data_models.emplace(name, MakeUnique<DataModel>(data_type_register));
  722. bool inserted = result.second;
  723. if (inserted)
  724. return DataModelConstructor(result.first->second.get());
  725. Log::Message(Log::LT_ERROR, "Data model name '%s' already exists.", name.c_str());
  726. return DataModelConstructor();
  727. }
  728. DataModelConstructor Context::GetDataModel(const String& name)
  729. {
  730. if (DataModel* model = GetDataModelPtr(name))
  731. return DataModelConstructor(model);
  732. Log::Message(Log::LT_ERROR, "Data model name '%s' could not be found.", name.c_str());
  733. return DataModelConstructor();
  734. }
  735. bool Context::RemoveDataModel(const String& name)
  736. {
  737. auto it = data_models.find(name);
  738. if (it == data_models.end())
  739. return false;
  740. DataModel* model = it->second.get();
  741. ElementList elements = model->GetAttachedModelRootElements();
  742. for (Element* element : elements)
  743. element->SetDataModel(nullptr);
  744. data_models.erase(it);
  745. return true;
  746. }
  747. void Context::OnElementDetach(Element* element)
  748. {
  749. auto it_hover = hover_chain.find(element);
  750. if (it_hover != hover_chain.end())
  751. {
  752. Dictionary parameters;
  753. GenerateMouseEventParameters(parameters, -1);
  754. element->DispatchEvent(EventId::Mouseout, parameters);
  755. hover_chain.erase(it_hover);
  756. if (hover == element)
  757. hover = nullptr;
  758. }
  759. auto it_active = std::find(active_chain.begin(), active_chain.end(), element);
  760. if (it_active != active_chain.end())
  761. {
  762. active_chain.erase(it_active);
  763. if (active == element)
  764. active = nullptr;
  765. }
  766. if (drag)
  767. {
  768. auto it = drag_hover_chain.find(element);
  769. if (it != drag_hover_chain.end())
  770. {
  771. drag_hover_chain.erase(it);
  772. if (drag_hover == element)
  773. drag_hover = nullptr;
  774. }
  775. if (drag == element)
  776. {
  777. // The dragged element is being removed, silently cancel the drag operation
  778. if (drag_started)
  779. ReleaseDragClone();
  780. drag = nullptr;
  781. drag_hover = nullptr;
  782. drag_hover_chain.clear();
  783. }
  784. }
  785. // Focus normally cleared and set by parent during Element::RemoveChild.
  786. // However, there are some exceptions, such as when an there are multiple
  787. // ElementDocuments in the hierarchy above the current element.
  788. if (element == focus)
  789. focus = nullptr;
  790. // If the element is a document lower down in the hierarchy, we may need to remove it from the focus history.
  791. if (element->GetOwnerDocument() == element)
  792. {
  793. auto it = std::find(document_focus_history.begin(), document_focus_history.end(), element);
  794. if (it != document_focus_history.end())
  795. document_focus_history.erase(it);
  796. }
  797. if (scroll_controller->GetTarget() == element)
  798. scroll_controller->Reset();
  799. }
  800. bool Context::OnFocusChange(Element* new_focus, bool focus_visible)
  801. {
  802. RMLUI_ASSERT(new_focus);
  803. ElementSet old_chain;
  804. ElementSet new_chain;
  805. Element* old_focus = focus;
  806. ElementDocument* old_document = old_focus ? old_focus->GetOwnerDocument() : nullptr;
  807. ElementDocument* new_document = new_focus->GetOwnerDocument();
  808. // If the current focus is modal and the new focus is cannot receive focus from modal, deny the request.
  809. if (old_document && old_document->IsModal() && (!new_document || !(new_document->IsModal() || new_document->IsFocusableFromModal())))
  810. return false;
  811. // Build the old chains
  812. Element* element = old_focus;
  813. while (element)
  814. {
  815. old_chain.insert(element);
  816. element = element->GetParentNode();
  817. }
  818. // Build the new chain
  819. element = new_focus;
  820. while (element)
  821. {
  822. new_chain.insert(element);
  823. element = element->GetParentNode();
  824. }
  825. // Send out blur/focus events.
  826. Dictionary parameters;
  827. SendEvents(old_chain, new_chain, EventId::Blur, parameters);
  828. if (focus_visible)
  829. parameters["focus_visible"] = true;
  830. SendEvents(new_chain, old_chain, EventId::Focus, parameters);
  831. focus = new_focus;
  832. // Raise the element's document to the front, if desired.
  833. ElementDocument* document = focus->GetOwnerDocument();
  834. if (document != nullptr)
  835. {
  836. Style::ZIndex z_index_property = document->GetComputedValues().z_index();
  837. if (z_index_property.type == Style::ZIndex::Auto)
  838. document->PullToFront();
  839. }
  840. // Update the focus history
  841. if (old_document != new_document)
  842. {
  843. // If documents have changed, add the new document to the end of the history
  844. ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), new_document);
  845. if (itr != document_focus_history.end())
  846. document_focus_history.erase(itr);
  847. if (new_document != nullptr)
  848. document_focus_history.push_back(new_document);
  849. }
  850. return true;
  851. }
  852. void Context::GenerateClickEvent(Element* element)
  853. {
  854. Dictionary parameters;
  855. GenerateMouseEventParameters(parameters, 0);
  856. element->DispatchEvent(EventId::Click, parameters);
  857. }
  858. void Context::UpdateHoverChain(Vector2i old_mouse_position, int key_modifier_state, Dictionary* out_parameters, Dictionary* out_drag_parameters)
  859. {
  860. const Vector2f position(mouse_position);
  861. Dictionary local_parameters, local_drag_parameters;
  862. Dictionary& parameters = out_parameters ? *out_parameters : local_parameters;
  863. Dictionary& drag_parameters = out_drag_parameters ? *out_drag_parameters : local_drag_parameters;
  864. // Generate the parameters for the mouse events (there could be a few!).
  865. GenerateMouseEventParameters(parameters);
  866. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  867. GenerateMouseEventParameters(drag_parameters);
  868. GenerateDragEventParameters(drag_parameters);
  869. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  870. // Send out drag events.
  871. if (drag)
  872. {
  873. if (mouse_position != old_mouse_position)
  874. {
  875. if (!drag_started)
  876. {
  877. Dictionary drag_start_parameters = drag_parameters;
  878. drag_start_parameters["mouse_x"] = old_mouse_position.x;
  879. drag_start_parameters["mouse_y"] = old_mouse_position.y;
  880. drag->DispatchEvent(EventId::Dragstart, drag_start_parameters);
  881. drag_started = true;
  882. if (drag->GetComputedValues().drag() == Style::Drag::Clone)
  883. {
  884. // Clone the element and attach it to the mouse cursor.
  885. CreateDragClone(drag);
  886. }
  887. }
  888. drag->DispatchEvent(EventId::Drag, drag_parameters);
  889. }
  890. }
  891. hover = mouse_active ? GetElementAtPoint(position) : nullptr;
  892. if (enable_cursor)
  893. {
  894. String new_cursor_name;
  895. if (scroll_controller->GetMode() == ScrollController::Mode::Autoscroll)
  896. new_cursor_name = scroll_controller->GetAutoscrollCursor(mouse_position, density_independent_pixel_ratio);
  897. else if (drag)
  898. new_cursor_name = drag->GetComputedValues().cursor();
  899. else if (hover)
  900. new_cursor_name = hover->GetComputedValues().cursor();
  901. if (new_cursor_name != cursor_name)
  902. {
  903. GetSystemInterface()->SetMouseCursor(new_cursor_name);
  904. cursor_name = new_cursor_name;
  905. }
  906. }
  907. // Build the new hover chain.
  908. ElementSet new_hover_chain;
  909. Element* element = hover;
  910. while (element != nullptr)
  911. {
  912. new_hover_chain.insert(element);
  913. element = element->GetParentNode();
  914. }
  915. // Send mouseout / mouseover events.
  916. SendEvents(hover_chain, new_hover_chain, EventId::Mouseout, parameters);
  917. SendEvents(new_hover_chain, hover_chain, EventId::Mouseover, parameters);
  918. // Send out drag events.
  919. if (drag && mouse_active)
  920. {
  921. drag_hover = GetElementAtPoint(position, drag);
  922. ElementSet new_drag_hover_chain;
  923. element = drag_hover;
  924. while (element != nullptr)
  925. {
  926. new_drag_hover_chain.insert(element);
  927. element = element->GetParentNode();
  928. }
  929. if (drag_started && drag_verbose)
  930. {
  931. // Send out ondragover and ondragout events as appropriate.
  932. SendEvents(drag_hover_chain, new_drag_hover_chain, EventId::Dragout, drag_parameters);
  933. SendEvents(new_drag_hover_chain, drag_hover_chain, EventId::Dragover, drag_parameters);
  934. }
  935. drag_hover_chain.swap(new_drag_hover_chain);
  936. }
  937. // Swap the new chain in.
  938. hover_chain.swap(new_hover_chain);
  939. }
  940. Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_element, Element* element) const
  941. {
  942. if (!element)
  943. {
  944. if (ignore_element == root.get())
  945. return nullptr;
  946. element = root.get();
  947. }
  948. bool is_modal = false;
  949. ElementDocument* focus_document = nullptr;
  950. // If we have modal focus, only check down documents that can receive focus from modals.
  951. if (element == root.get() && focus)
  952. {
  953. focus_document = focus->GetOwnerDocument();
  954. if (focus_document && focus_document->IsModal())
  955. is_modal = true;
  956. }
  957. // Check any elements within our stacking context. We want to return the lowest-down element
  958. // that is under the cursor.
  959. if (element->local_stacking_context)
  960. {
  961. if (element->stacking_context_dirty)
  962. element->BuildLocalStackingContext();
  963. for (int i = (int)element->stacking_context.size() - 1; i >= 0; --i)
  964. {
  965. Element* stacking_child = element->stacking_context[i];
  966. if (ignore_element)
  967. {
  968. // Check if the element is a descendant of the element we're ignoring.
  969. Element* element_hierarchy = stacking_child;
  970. while (element_hierarchy)
  971. {
  972. if (element_hierarchy == ignore_element)
  973. break;
  974. element_hierarchy = element_hierarchy->GetParentNode();
  975. }
  976. if (element_hierarchy)
  977. continue;
  978. }
  979. if (is_modal)
  980. {
  981. ElementDocument* child_document = stacking_child->GetOwnerDocument();
  982. if (!child_document || !(child_document == focus_document || child_document->IsFocusableFromModal()))
  983. continue;
  984. }
  985. Element* child_element = GetElementAtPoint(point, ignore_element, stacking_child);
  986. if (child_element)
  987. return child_element;
  988. }
  989. }
  990. // Ignore elements whose pointer events are disabled.
  991. if (element->GetComputedValues().pointer_events() == Style::PointerEvents::None)
  992. return nullptr;
  993. // Projection may fail if we have a singular transformation matrix.
  994. bool projection_result = element->Project(point);
  995. // Check if the point is actually within this element.
  996. bool within_element = (projection_result && element->IsPointWithinElement(point));
  997. if (within_element)
  998. {
  999. // The element may have been clipped out of view if it overflows an ancestor, so check its clipping region.
  1000. Rectanglei clip_region;
  1001. if (ElementUtilities::GetClippingRegion(element, clip_region))
  1002. within_element = clip_region.Contains(Vector2i(point));
  1003. }
  1004. if (within_element)
  1005. return element;
  1006. return nullptr;
  1007. }
  1008. void Context::CreateDragClone(Element* element)
  1009. {
  1010. RMLUI_ASSERTMSG(cursor_proxy, "Unable to create drag clone, no cursor proxy document.");
  1011. ReleaseDragClone();
  1012. // Instance the drag clone.
  1013. ElementPtr element_drag_clone = element->Clone();
  1014. if (!element_drag_clone)
  1015. {
  1016. Log::Message(Log::LT_ERROR, "Unable to duplicate drag clone.");
  1017. return;
  1018. }
  1019. // Set the style sheet on the cursor proxy.
  1020. if (ElementDocument* document = element->GetOwnerDocument())
  1021. {
  1022. // Borrow the target document's style sheet. Sharing style sheet containers should be used with care, and
  1023. // only within the same context.
  1024. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheetContainer(document->style_sheet_container);
  1025. }
  1026. drag_clone = element_drag_clone.get();
  1027. // Append the clone to the cursor proxy element.
  1028. cursor_proxy->AppendChild(std::move(element_drag_clone));
  1029. // Position the clone. Use projected mouse coordinates to handle any ancestor transforms.
  1030. const Vector2f absolute_pos = element->GetAbsoluteOffset(BoxArea::Border);
  1031. Vector2f projected_mouse_position = Vector2f(mouse_position);
  1032. if (Element* parent = element->GetParentNode())
  1033. parent->Project(projected_mouse_position);
  1034. drag_clone->SetProperty(PropertyId::Position, Property(Style::Position::Absolute));
  1035. drag_clone->SetProperty(PropertyId::Left, Property(absolute_pos.x - projected_mouse_position.x, Unit::PX));
  1036. drag_clone->SetProperty(PropertyId::Top, Property(absolute_pos.y - projected_mouse_position.y, Unit::PX));
  1037. // We remove margins so that percentage- and auto-margins are evaluated correctly.
  1038. drag_clone->SetProperty(PropertyId::MarginLeft, Property(0.f, Unit::PX));
  1039. drag_clone->SetProperty(PropertyId::MarginTop, Property(0.f, Unit::PX));
  1040. drag_clone->SetPseudoClass("drag", true);
  1041. }
  1042. void Context::ReleaseDragClone()
  1043. {
  1044. if (drag_clone)
  1045. {
  1046. cursor_proxy->RemoveChild(drag_clone);
  1047. drag_clone = nullptr;
  1048. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheetContainer(nullptr);
  1049. }
  1050. }
  1051. void Context::PerformSmoothscrollOnTarget(Element* target, Vector2f delta_offset, ScrollBehavior scroll_behavior)
  1052. {
  1053. scroll_controller->ActivateSmoothscroll(target, delta_offset, scroll_behavior);
  1054. }
  1055. DataModel* Context::GetDataModelPtr(const String& name) const
  1056. {
  1057. auto it = data_models.find(name);
  1058. if (it != data_models.end())
  1059. return it->second.get();
  1060. return nullptr;
  1061. }
  1062. void Context::GenerateKeyEventParameters(Dictionary& parameters, Input::KeyIdentifier key_identifier)
  1063. {
  1064. parameters["key_identifier"] = (int)key_identifier;
  1065. }
  1066. void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_index)
  1067. {
  1068. parameters.reserve(3);
  1069. parameters["mouse_x"] = mouse_position.x;
  1070. parameters["mouse_y"] = mouse_position.y;
  1071. if (button_index >= 0)
  1072. parameters["button"] = button_index;
  1073. }
  1074. void Context::GenerateKeyModifierEventParameters(Dictionary& parameters, int key_modifier_state)
  1075. {
  1076. static const String property_names[] = {"ctrl_key", "shift_key", "alt_key", "meta_key", "caps_lock_key", "num_lock_key", "scroll_lock_key"};
  1077. for (int i = 0; i < 7; i++)
  1078. parameters[property_names[i]] = (int)((key_modifier_state & (1 << i)) > 0);
  1079. }
  1080. void Context::GenerateDragEventParameters(Dictionary& parameters)
  1081. {
  1082. parameters["drag_element"] = (void*)drag;
  1083. }
  1084. void Context::ReleaseUnloadedDocuments()
  1085. {
  1086. if (!unloaded_documents.empty())
  1087. {
  1088. OwnedElementList documents = std::move(unloaded_documents);
  1089. unloaded_documents.clear();
  1090. // Clear the deleted list.
  1091. for (size_t i = 0; i < documents.size(); ++i)
  1092. documents[i]->GetEventDispatcher()->DetachAllEvents();
  1093. documents.clear();
  1094. }
  1095. }
  1096. using ElementObserverList = Vector<ObserverPtr<Element>>;
  1097. class ElementObserverListBackInserter {
  1098. public:
  1099. using iterator_category = std::output_iterator_tag;
  1100. using value_type = void;
  1101. using difference_type = void;
  1102. using pointer = void;
  1103. using reference = void;
  1104. using container_type = ElementObserverList;
  1105. ElementObserverListBackInserter(ElementObserverList& elements) : elements(&elements) {}
  1106. ElementObserverListBackInserter& operator=(Element* element)
  1107. {
  1108. elements->push_back(element->GetObserverPtr());
  1109. return *this;
  1110. }
  1111. ElementObserverListBackInserter& operator*() { return *this; }
  1112. ElementObserverListBackInserter& operator++() { return *this; }
  1113. ElementObserverListBackInserter& operator++(int) { return *this; }
  1114. private:
  1115. ElementObserverList* elements;
  1116. };
  1117. void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, EventId id, const Dictionary& parameters)
  1118. {
  1119. // We put our elements in observer pointers in case some of them are deleted during dispatch.
  1120. ElementObserverList elements;
  1121. std::set_difference(old_items.begin(), old_items.end(), new_items.begin(), new_items.end(), ElementObserverListBackInserter(elements));
  1122. for (auto& element : elements)
  1123. {
  1124. if (element)
  1125. element->DispatchEvent(id, parameters);
  1126. }
  1127. }
  1128. void Context::Release()
  1129. {
  1130. if (instancer)
  1131. {
  1132. instancer->ReleaseContext(this);
  1133. }
  1134. }
  1135. void Context::SetDocumentsBaseTag(const String& tag)
  1136. {
  1137. documents_base_tag = tag;
  1138. }
  1139. const String& Context::GetDocumentsBaseTag()
  1140. {
  1141. return documents_base_tag;
  1142. }
  1143. void Context::RequestNextUpdate(double delay)
  1144. {
  1145. RMLUI_ASSERT(delay >= 0.0);
  1146. next_update_timeout = Math::Min(next_update_timeout, delay);
  1147. }
  1148. double Context::GetNextUpdateDelay() const
  1149. {
  1150. return next_update_timeout;
  1151. }
  1152. } // namespace Rml