Context.cpp 41 KB

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