Context.cpp 35 KB

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