Context.cpp 36 KB

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