Context.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  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. // If the document of the new focus has been closed, deny the request.
  812. if (std::find_if(unloaded_documents.begin(), unloaded_documents.end(),
  813. [&](const auto& unloaded_document) { return unloaded_document.get() == new_document; }) != unloaded_documents.end())
  814. {
  815. return false;
  816. }
  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. // Send out blur/focus events.
  832. Dictionary parameters;
  833. SendEvents(old_chain, new_chain, EventId::Blur, parameters);
  834. if (focus_visible)
  835. parameters["focus_visible"] = true;
  836. SendEvents(new_chain, old_chain, EventId::Focus, parameters);
  837. focus = new_focus;
  838. // Raise the element's document to the front, if desired.
  839. ElementDocument* document = focus->GetOwnerDocument();
  840. if (document != nullptr)
  841. {
  842. Style::ZIndex z_index_property = document->GetComputedValues().z_index();
  843. if (z_index_property.type == Style::ZIndex::Auto)
  844. document->PullToFront();
  845. }
  846. // Update the focus history
  847. if (old_document != new_document)
  848. {
  849. // If documents have changed, add the new document to the end of the history
  850. ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), new_document);
  851. if (itr != document_focus_history.end())
  852. document_focus_history.erase(itr);
  853. if (new_document != nullptr)
  854. document_focus_history.push_back(new_document);
  855. }
  856. return true;
  857. }
  858. void Context::GenerateClickEvent(Element* element)
  859. {
  860. Dictionary parameters;
  861. GenerateMouseEventParameters(parameters, 0);
  862. element->DispatchEvent(EventId::Click, parameters);
  863. }
  864. void Context::UpdateHoverChain(Vector2i old_mouse_position, int key_modifier_state, Dictionary* out_parameters, Dictionary* out_drag_parameters)
  865. {
  866. const Vector2f position(mouse_position);
  867. Dictionary local_parameters, local_drag_parameters;
  868. Dictionary& parameters = out_parameters ? *out_parameters : local_parameters;
  869. Dictionary& drag_parameters = out_drag_parameters ? *out_drag_parameters : local_drag_parameters;
  870. // Generate the parameters for the mouse events (there could be a few!).
  871. GenerateMouseEventParameters(parameters);
  872. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  873. GenerateMouseEventParameters(drag_parameters);
  874. GenerateDragEventParameters(drag_parameters);
  875. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  876. // Send out drag events.
  877. if (drag)
  878. {
  879. if (mouse_position != old_mouse_position)
  880. {
  881. if (!drag_started)
  882. {
  883. Dictionary drag_start_parameters = drag_parameters;
  884. drag_start_parameters["mouse_x"] = old_mouse_position.x;
  885. drag_start_parameters["mouse_y"] = old_mouse_position.y;
  886. drag->DispatchEvent(EventId::Dragstart, drag_start_parameters);
  887. drag_started = true;
  888. if (drag->GetComputedValues().drag() == Style::Drag::Clone)
  889. {
  890. // Clone the element and attach it to the mouse cursor.
  891. CreateDragClone(drag);
  892. }
  893. }
  894. drag->DispatchEvent(EventId::Drag, drag_parameters);
  895. }
  896. }
  897. hover = mouse_active ? GetElementAtPoint(position) : nullptr;
  898. if (enable_cursor)
  899. {
  900. String new_cursor_name;
  901. if (scroll_controller->GetMode() == ScrollController::Mode::Autoscroll)
  902. new_cursor_name = scroll_controller->GetAutoscrollCursor(mouse_position, density_independent_pixel_ratio);
  903. else if (drag)
  904. new_cursor_name = drag->GetComputedValues().cursor();
  905. else if (hover)
  906. new_cursor_name = hover->GetComputedValues().cursor();
  907. if (new_cursor_name != cursor_name)
  908. {
  909. GetSystemInterface()->SetMouseCursor(new_cursor_name);
  910. cursor_name = new_cursor_name;
  911. }
  912. }
  913. // Build the new hover chain.
  914. ElementSet new_hover_chain;
  915. Element* element = hover;
  916. while (element != nullptr)
  917. {
  918. new_hover_chain.insert(element);
  919. element = element->GetParentNode();
  920. }
  921. // Send mouseout / mouseover events.
  922. SendEvents(hover_chain, new_hover_chain, EventId::Mouseout, parameters);
  923. SendEvents(new_hover_chain, hover_chain, EventId::Mouseover, parameters);
  924. // Send out drag events.
  925. if (drag && mouse_active)
  926. {
  927. drag_hover = GetElementAtPoint(position, drag);
  928. ElementSet new_drag_hover_chain;
  929. element = drag_hover;
  930. while (element != nullptr)
  931. {
  932. new_drag_hover_chain.insert(element);
  933. element = element->GetParentNode();
  934. }
  935. if (drag_started && drag_verbose)
  936. {
  937. // Send out ondragover and ondragout events as appropriate.
  938. SendEvents(drag_hover_chain, new_drag_hover_chain, EventId::Dragout, drag_parameters);
  939. SendEvents(new_drag_hover_chain, drag_hover_chain, EventId::Dragover, drag_parameters);
  940. }
  941. drag_hover_chain.swap(new_drag_hover_chain);
  942. }
  943. // Swap the new chain in.
  944. hover_chain.swap(new_hover_chain);
  945. }
  946. Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_element, Element* element) const
  947. {
  948. if (!element)
  949. {
  950. if (ignore_element == root.get())
  951. return nullptr;
  952. element = root.get();
  953. }
  954. bool is_modal = false;
  955. ElementDocument* focus_document = nullptr;
  956. // If we have modal focus, only check down documents that can receive focus from modals.
  957. if (element == root.get() && focus)
  958. {
  959. focus_document = focus->GetOwnerDocument();
  960. if (focus_document && focus_document->IsModal())
  961. is_modal = true;
  962. }
  963. // Check any elements within our stacking context. We want to return the lowest-down element
  964. // that is under the cursor.
  965. if (element->local_stacking_context)
  966. {
  967. if (element->stacking_context_dirty)
  968. element->BuildLocalStackingContext();
  969. for (int i = (int)element->stacking_context.size() - 1; i >= 0; --i)
  970. {
  971. Element* stacking_child = element->stacking_context[i];
  972. if (ignore_element)
  973. {
  974. // Check if the element is a descendant of the element we're ignoring.
  975. Element* element_hierarchy = stacking_child;
  976. while (element_hierarchy)
  977. {
  978. if (element_hierarchy == ignore_element)
  979. break;
  980. element_hierarchy = element_hierarchy->GetParentNode();
  981. }
  982. if (element_hierarchy)
  983. continue;
  984. }
  985. if (is_modal)
  986. {
  987. ElementDocument* child_document = stacking_child->GetOwnerDocument();
  988. if (!child_document || !(child_document == focus_document || child_document->IsFocusableFromModal()))
  989. continue;
  990. }
  991. Element* child_element = GetElementAtPoint(point, ignore_element, stacking_child);
  992. if (child_element)
  993. return child_element;
  994. }
  995. }
  996. // Ignore elements whose pointer events are disabled.
  997. if (element->GetComputedValues().pointer_events() == Style::PointerEvents::None)
  998. return nullptr;
  999. // Projection may fail if we have a singular transformation matrix.
  1000. bool projection_result = element->Project(point);
  1001. // Check if the point is actually within this element.
  1002. bool within_element = (projection_result && element->IsPointWithinElement(point));
  1003. if (within_element)
  1004. {
  1005. // The element may have been clipped out of view if it overflows an ancestor, so check its clipping region.
  1006. Rectanglei clip_region;
  1007. if (ElementUtilities::GetClippingRegion(element, clip_region))
  1008. within_element = clip_region.Contains(Vector2i(point));
  1009. }
  1010. if (within_element)
  1011. return element;
  1012. return nullptr;
  1013. }
  1014. void Context::CreateDragClone(Element* element)
  1015. {
  1016. RMLUI_ASSERTMSG(cursor_proxy, "Unable to create drag clone, no cursor proxy document.");
  1017. ReleaseDragClone();
  1018. // Instance the drag clone.
  1019. ElementPtr element_drag_clone = element->Clone();
  1020. if (!element_drag_clone)
  1021. {
  1022. Log::Message(Log::LT_ERROR, "Unable to duplicate drag clone.");
  1023. return;
  1024. }
  1025. // Set the style sheet on the cursor proxy.
  1026. if (ElementDocument* document = element->GetOwnerDocument())
  1027. {
  1028. // Borrow the target document's style sheet. Sharing style sheet containers should be used with care, and
  1029. // only within the same context.
  1030. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheetContainer(document->style_sheet_container);
  1031. }
  1032. drag_clone = element_drag_clone.get();
  1033. // Append the clone to the cursor proxy element.
  1034. cursor_proxy->AppendChild(std::move(element_drag_clone));
  1035. // Position the clone. Use projected mouse coordinates to handle any ancestor transforms.
  1036. const Vector2f absolute_pos = element->GetAbsoluteOffset(BoxArea::Border);
  1037. Vector2f projected_mouse_position = Vector2f(mouse_position);
  1038. if (Element* parent = element->GetParentNode())
  1039. parent->Project(projected_mouse_position);
  1040. drag_clone->SetProperty(PropertyId::Position, Property(Style::Position::Absolute));
  1041. drag_clone->SetProperty(PropertyId::Left, Property(absolute_pos.x - projected_mouse_position.x, Unit::PX));
  1042. drag_clone->SetProperty(PropertyId::Top, Property(absolute_pos.y - projected_mouse_position.y, Unit::PX));
  1043. // We remove margins so that percentage- and auto-margins are evaluated correctly.
  1044. drag_clone->SetProperty(PropertyId::MarginLeft, Property(0.f, Unit::PX));
  1045. drag_clone->SetProperty(PropertyId::MarginTop, Property(0.f, Unit::PX));
  1046. drag_clone->SetPseudoClass("drag", true);
  1047. }
  1048. void Context::ReleaseDragClone()
  1049. {
  1050. if (drag_clone)
  1051. {
  1052. cursor_proxy->RemoveChild(drag_clone);
  1053. drag_clone = nullptr;
  1054. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheetContainer(nullptr);
  1055. }
  1056. }
  1057. void Context::PerformSmoothscrollOnTarget(Element* target, Vector2f delta_offset, ScrollBehavior scroll_behavior)
  1058. {
  1059. scroll_controller->ActivateSmoothscroll(target, delta_offset, scroll_behavior);
  1060. }
  1061. DataModel* Context::GetDataModelPtr(const String& name) const
  1062. {
  1063. auto it = data_models.find(name);
  1064. if (it != data_models.end())
  1065. return it->second.get();
  1066. return nullptr;
  1067. }
  1068. void Context::GenerateKeyEventParameters(Dictionary& parameters, Input::KeyIdentifier key_identifier)
  1069. {
  1070. parameters["key_identifier"] = (int)key_identifier;
  1071. }
  1072. void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_index)
  1073. {
  1074. parameters.reserve(3);
  1075. parameters["mouse_x"] = mouse_position.x;
  1076. parameters["mouse_y"] = mouse_position.y;
  1077. if (button_index >= 0)
  1078. parameters["button"] = button_index;
  1079. }
  1080. void Context::GenerateKeyModifierEventParameters(Dictionary& parameters, int key_modifier_state)
  1081. {
  1082. static const String property_names[] = {"ctrl_key", "shift_key", "alt_key", "meta_key", "caps_lock_key", "num_lock_key", "scroll_lock_key"};
  1083. for (int i = 0; i < 7; i++)
  1084. parameters[property_names[i]] = (int)((key_modifier_state & (1 << i)) > 0);
  1085. }
  1086. void Context::GenerateDragEventParameters(Dictionary& parameters)
  1087. {
  1088. parameters["drag_element"] = (void*)drag;
  1089. }
  1090. void Context::ReleaseUnloadedDocuments()
  1091. {
  1092. if (!unloaded_documents.empty())
  1093. {
  1094. OwnedElementList documents = std::move(unloaded_documents);
  1095. unloaded_documents.clear();
  1096. // Clear the deleted list.
  1097. for (size_t i = 0; i < documents.size(); ++i)
  1098. documents[i]->GetEventDispatcher()->DetachAllEvents();
  1099. documents.clear();
  1100. }
  1101. }
  1102. using ElementObserverList = Vector<ObserverPtr<Element>>;
  1103. class ElementObserverListBackInserter {
  1104. public:
  1105. using iterator_category = std::output_iterator_tag;
  1106. using value_type = void;
  1107. using difference_type = void;
  1108. using pointer = void;
  1109. using reference = void;
  1110. using container_type = ElementObserverList;
  1111. ElementObserverListBackInserter(ElementObserverList& elements) : elements(&elements) {}
  1112. ElementObserverListBackInserter& operator=(Element* element)
  1113. {
  1114. elements->push_back(element->GetObserverPtr());
  1115. return *this;
  1116. }
  1117. ElementObserverListBackInserter& operator*() { return *this; }
  1118. ElementObserverListBackInserter& operator++() { return *this; }
  1119. ElementObserverListBackInserter& operator++(int) { return *this; }
  1120. private:
  1121. ElementObserverList* elements;
  1122. };
  1123. void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, EventId id, const Dictionary& parameters)
  1124. {
  1125. // We put our elements in observer pointers in case some of them are deleted during dispatch.
  1126. ElementObserverList elements;
  1127. std::set_difference(old_items.begin(), old_items.end(), new_items.begin(), new_items.end(), ElementObserverListBackInserter(elements));
  1128. for (auto& element : elements)
  1129. {
  1130. if (element)
  1131. element->DispatchEvent(id, parameters);
  1132. }
  1133. }
  1134. void Context::Release()
  1135. {
  1136. if (instancer)
  1137. {
  1138. instancer->ReleaseContext(this);
  1139. }
  1140. }
  1141. void Context::SetDocumentsBaseTag(const String& tag)
  1142. {
  1143. documents_base_tag = tag;
  1144. }
  1145. const String& Context::GetDocumentsBaseTag()
  1146. {
  1147. return documents_base_tag;
  1148. }
  1149. void Context::RequestNextUpdate(double delay)
  1150. {
  1151. RMLUI_ASSERT(delay >= 0.0);
  1152. next_update_timeout = Math::Min(next_update_timeout, delay);
  1153. }
  1154. double Context::GetNextUpdateDelay() const
  1155. {
  1156. return next_update_timeout;
  1157. }
  1158. } // namespace Rml