Context.cpp 41 KB

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