Context.cpp 49 KB

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