Context.cpp 49 KB

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