Context.cpp 44 KB

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