Context.cpp 45 KB

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