Context.cpp 42 KB

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