Context.cpp 33 KB

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