Context.cpp 42 KB

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