Context.cpp 43 KB

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