Context.cpp 37 KB

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