Context.cpp 43 KB

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