Context.cpp 48 KB

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