Context.cpp 33 KB

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