Context.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../../Include/RmlUi/Core/Context.h"
  29. #include "../../Include/RmlUi/Core/ContextInstancer.h"
  30. #include "../../Include/RmlUi/Core/Core.h"
  31. #include "../../Include/RmlUi/Core/ElementDocument.h"
  32. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  33. #include "../../Include/RmlUi/Core/Factory.h"
  34. #include "../../Include/RmlUi/Core/Profiling.h"
  35. #include "../../Include/RmlUi/Core/RenderInterface.h"
  36. #include "../../Include/RmlUi/Core/StreamMemory.h"
  37. #include "../../Include/RmlUi/Core/SystemInterface.h"
  38. #include "../../Include/RmlUi/Core/DataModel.h"
  39. #include "../../Include/RmlUi/Core/StreamMemory.h"
  40. #include "EventDispatcher.h"
  41. #include "PluginRegistry.h"
  42. #include "StreamFile.h"
  43. #include <algorithm>
  44. #include <iterator>
  45. namespace Rml {
  46. static constexpr float DOUBLE_CLICK_TIME = 0.5f; // [s]
  47. static constexpr float DOUBLE_CLICK_MAX_DIST = 3.f; // [dp]
  48. Context::Context(const String& name) : name(name), dimensions(0, 0), density_independent_pixel_ratio(1.0f), mouse_position(0, 0), clip_origin(-1, -1), clip_dimensions(-1, -1)
  49. {
  50. instancer = nullptr;
  51. // Initialise this to nullptr; this will be set in Rml::CreateContext().
  52. render_interface = nullptr;
  53. root = Factory::InstanceElement(nullptr, "*", "#root", XMLAttributes());
  54. root->SetId(name);
  55. root->SetOffset(Vector2f(0, 0), nullptr);
  56. root->SetProperty(PropertyId::ZIndex, Property(0, Property::NUMBER));
  57. cursor_proxy = Factory::InstanceElement(nullptr, documents_base_tag, documents_base_tag, XMLAttributes());
  58. ElementDocument* cursor_proxy_document = rmlui_dynamic_cast< ElementDocument* >(cursor_proxy.get());
  59. if (cursor_proxy_document)
  60. cursor_proxy_document->context = this;
  61. else
  62. cursor_proxy.reset();
  63. enable_cursor = true;
  64. document_focus_history.push_back(root.get());
  65. focus = root.get();
  66. hover = nullptr;
  67. active = nullptr;
  68. drag = nullptr;
  69. drag_started = false;
  70. drag_verbose = false;
  71. drag_clone = nullptr;
  72. drag_hover = nullptr;
  73. last_click_element = nullptr;
  74. last_click_time = 0;
  75. last_click_mouse_position = Vector2i(0, 0);
  76. }
  77. Context::~Context()
  78. {
  79. PluginRegistry::NotifyContextDestroy(this);
  80. UnloadAllDocuments();
  81. ReleaseUnloadedDocuments();
  82. cursor_proxy.reset();
  83. root.reset();
  84. instancer = nullptr;
  85. render_interface = nullptr;
  86. }
  87. // Returns the name of the context.
  88. const String& Context::GetName() const
  89. {
  90. return name;
  91. }
  92. // Changes the dimensions of the screen.
  93. void Context::SetDimensions(const Vector2i& _dimensions)
  94. {
  95. if (dimensions != _dimensions)
  96. {
  97. dimensions = _dimensions;
  98. root->SetBox(Box(Vector2f((float) dimensions.x, (float) dimensions.y)));
  99. root->DirtyLayout();
  100. for (int i = 0; i < root->GetNumChildren(); ++i)
  101. {
  102. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  103. if (document != nullptr)
  104. {
  105. document->DirtyLayout();
  106. document->DirtyPosition();
  107. document->DispatchEvent(EventId::Resize, Dictionary());
  108. }
  109. }
  110. clip_dimensions = dimensions;
  111. }
  112. }
  113. // Returns the dimensions of the screen.
  114. const Vector2i& Context::GetDimensions() const
  115. {
  116. return dimensions;
  117. }
  118. void Context::SetDensityIndependentPixelRatio(float _density_independent_pixel_ratio)
  119. {
  120. if (density_independent_pixel_ratio != _density_independent_pixel_ratio)
  121. {
  122. density_independent_pixel_ratio = _density_independent_pixel_ratio;
  123. for (int i = 0; i < root->GetNumChildren(); ++i)
  124. {
  125. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  126. if (document != nullptr)
  127. {
  128. document->DirtyDpProperties();
  129. }
  130. }
  131. }
  132. }
  133. float Context::GetDensityIndependentPixelRatio() const
  134. {
  135. return density_independent_pixel_ratio;
  136. }
  137. // Updates all elements in the element tree.
  138. bool Context::Update()
  139. {
  140. RMLUI_ZoneScoped;
  141. 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& instancer_name)
  177. {
  178. ElementPtr element = Factory::InstanceElement(nullptr, instancer_name, documents_base_tag, XMLAttributes());
  179. if (!element)
  180. {
  181. Log::Message(Log::LT_ERROR, "Failed to instance document on instancer_name '%s', instancer returned nullptr.", instancer_name.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 instancer_name '%s', Found type '%s', was expecting derivative of ElementDocument.", instancer_name.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 = MakeUnique<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 = MakeUnique<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. active_chain.insert(active_chain.end(), hover_chain.begin(), hover_chain.end());
  533. if (propagate)
  534. {
  535. // Traverse down the hierarchy of the newly focused 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. std::for_each(active_chain.begin(), active_chain.end(), [](Element* element) {
  579. element->SetPseudoClass("active", false);
  580. });
  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. DataModelConstructor Context::CreateDataModel(const String& name)
  657. {
  658. if (!data_type_register)
  659. data_type_register = MakeUnique<DataTypeRegister>();
  660. auto result = data_models.emplace(name, MakeUnique<DataModel>(data_type_register->GetTransformFuncRegister()));
  661. bool inserted = result.second;
  662. if (inserted)
  663. return DataModelConstructor(result.first->second.get(), data_type_register.get());
  664. Log::Message(Log::LT_ERROR, "Data model name '%s' already exists.", name.c_str());
  665. return DataModelConstructor();
  666. }
  667. DataModelConstructor Context::GetDataModel(const String& name)
  668. {
  669. if (data_type_register)
  670. {
  671. if (DataModel* model = GetDataModelPtr(name))
  672. return DataModelConstructor(model, data_type_register.get());
  673. }
  674. Log::Message(Log::LT_ERROR, "Data model name '%s' could not be found.", name.c_str());
  675. return DataModelConstructor();
  676. }
  677. bool Context::RemoveDataModel(const String& name)
  678. {
  679. auto it = data_models.find(name);
  680. if (it == data_models.end())
  681. return false;
  682. DataModel* model = it->second.get();
  683. ElementList elements = model->GetAttachedModelRootElements();
  684. for (Element* element : elements)
  685. element->SetDataModel(nullptr);
  686. data_models.erase(it);
  687. return true;
  688. }
  689. // Internal callback for when an element is removed from the hierarchy.
  690. void Context::OnElementDetach(Element* element)
  691. {
  692. auto it_hover = hover_chain.find(element);
  693. if (it_hover != hover_chain.end())
  694. {
  695. Dictionary parameters;
  696. GenerateMouseEventParameters(parameters, -1);
  697. element->DispatchEvent(EventId::Mouseout, parameters);
  698. hover_chain.erase(it_hover);
  699. if (hover == element)
  700. hover = nullptr;
  701. }
  702. auto it_active = std::find(active_chain.begin(), active_chain.end(), element);
  703. if (it_active != active_chain.end())
  704. {
  705. active_chain.erase(it_active);
  706. if (active == element)
  707. active = nullptr;
  708. }
  709. if (drag)
  710. {
  711. auto it = drag_hover_chain.find(element);
  712. if (it != drag_hover_chain.end())
  713. {
  714. drag_hover_chain.erase(it);
  715. if (drag_hover == element)
  716. drag_hover = nullptr;
  717. }
  718. if (drag == element)
  719. {
  720. // The dragged element is being removed, silently cancel the drag operation
  721. if (drag_started)
  722. ReleaseDragClone();
  723. drag = nullptr;
  724. drag_hover = nullptr;
  725. drag_hover_chain.clear();
  726. }
  727. }
  728. // Focus normally cleared and set by parent during Element::RemoveChild.
  729. // However, there are some exceptions, such as when an there are multiple
  730. // ElementDocuments in the hierarchy above the current element.
  731. if (element == focus)
  732. focus = nullptr;
  733. // If the element is a document lower down in the hierarchy, we may need to remove it from the focus history.
  734. if (element->GetOwnerDocument() == element)
  735. {
  736. auto it = std::find(document_focus_history.begin(), document_focus_history.end(), element);
  737. if (it != document_focus_history.end())
  738. document_focus_history.erase(it);
  739. }
  740. }
  741. // Internal callback for when a new element gains focus
  742. bool Context::OnFocusChange(Element* new_focus)
  743. {
  744. RMLUI_ASSERT(new_focus);
  745. ElementSet old_chain;
  746. ElementSet new_chain;
  747. Element* old_focus = focus;
  748. ElementDocument* old_document = old_focus ? old_focus->GetOwnerDocument() : nullptr;
  749. ElementDocument* new_document = new_focus->GetOwnerDocument();
  750. // If the current focus is modal and the new focus is not modal, deny the request
  751. if (old_document && old_document->IsModal() && (!new_document || !new_document->GetOwnerDocument()->IsModal()))
  752. return false;
  753. // Build the old chains
  754. Element* element = old_focus;
  755. while (element)
  756. {
  757. old_chain.insert(element);
  758. element = element->GetParentNode();
  759. }
  760. // Build the new chain
  761. element = new_focus;
  762. while (element)
  763. {
  764. new_chain.insert(element);
  765. element = element->GetParentNode();
  766. }
  767. Dictionary parameters;
  768. // Send out blur/focus events.
  769. SendEvents(old_chain, new_chain, EventId::Blur, parameters);
  770. SendEvents(new_chain, old_chain, EventId::Focus, parameters);
  771. focus = new_focus;
  772. // Raise the element's document to the front, if desired.
  773. ElementDocument* document = focus->GetOwnerDocument();
  774. if (document != nullptr)
  775. {
  776. Style::ZIndex z_index_property = document->GetComputedValues().z_index;
  777. if (z_index_property.type == Style::ZIndex::Auto)
  778. document->PullToFront();
  779. }
  780. // Update the focus history
  781. if (old_document != new_document)
  782. {
  783. // If documents have changed, add the new document to the end of the history
  784. ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), new_document);
  785. if (itr != document_focus_history.end())
  786. document_focus_history.erase(itr);
  787. if (new_document != nullptr)
  788. document_focus_history.push_back(new_document);
  789. }
  790. return true;
  791. }
  792. // Generates an event for faking clicks on an element.
  793. void Context::GenerateClickEvent(Element* element)
  794. {
  795. Dictionary parameters;
  796. GenerateMouseEventParameters(parameters, 0);
  797. element->DispatchEvent(EventId::Click, parameters);
  798. }
  799. // Updates the current hover elements, sending required events.
  800. void Context::UpdateHoverChain(const Dictionary& parameters, const Dictionary& drag_parameters, const Vector2i& old_mouse_position)
  801. {
  802. Vector2f position((float) mouse_position.x, (float) mouse_position.y);
  803. // Send out drag events.
  804. if (drag)
  805. {
  806. if (mouse_position != old_mouse_position)
  807. {
  808. if (!drag_started)
  809. {
  810. Dictionary drag_start_parameters = drag_parameters;
  811. drag_start_parameters["mouse_x"] = old_mouse_position.x;
  812. drag_start_parameters["mouse_y"] = old_mouse_position.y;
  813. drag->DispatchEvent(EventId::Dragstart, drag_start_parameters);
  814. drag_started = true;
  815. if (drag->GetComputedValues().drag == Style::Drag::Clone)
  816. {
  817. // Clone the element and attach it to the mouse cursor.
  818. CreateDragClone(drag);
  819. }
  820. }
  821. drag->DispatchEvent(EventId::Drag, drag_parameters);
  822. }
  823. }
  824. hover = GetElementAtPoint(position);
  825. if(enable_cursor)
  826. {
  827. String new_cursor_name;
  828. if(drag)
  829. new_cursor_name = drag->GetComputedValues().cursor;
  830. else if (hover)
  831. new_cursor_name = hover->GetComputedValues().cursor;
  832. if(new_cursor_name != cursor_name)
  833. {
  834. GetSystemInterface()->SetMouseCursor(new_cursor_name);
  835. cursor_name = new_cursor_name;
  836. }
  837. }
  838. // Build the new hover chain.
  839. ElementSet new_hover_chain;
  840. Element* element = hover;
  841. while (element != nullptr)
  842. {
  843. new_hover_chain.insert(element);
  844. element = element->GetParentNode();
  845. }
  846. // Send mouseout / mouseover events.
  847. SendEvents(hover_chain, new_hover_chain, EventId::Mouseout, parameters);
  848. SendEvents(new_hover_chain, hover_chain, EventId::Mouseover, parameters);
  849. // Send out drag events.
  850. if (drag)
  851. {
  852. drag_hover = GetElementAtPoint(position, drag);
  853. ElementSet new_drag_hover_chain;
  854. element = drag_hover;
  855. while (element != nullptr)
  856. {
  857. new_drag_hover_chain.insert(element);
  858. element = element->GetParentNode();
  859. }
  860. if (drag_started &&
  861. drag_verbose)
  862. {
  863. // Send out ondragover and ondragout events as appropriate.
  864. SendEvents(drag_hover_chain, new_drag_hover_chain, EventId::Dragout, drag_parameters);
  865. SendEvents(new_drag_hover_chain, drag_hover_chain, EventId::Dragover, drag_parameters);
  866. }
  867. drag_hover_chain.swap(new_drag_hover_chain);
  868. }
  869. // Swap the new chain in.
  870. hover_chain.swap(new_hover_chain);
  871. }
  872. // Returns the youngest descendent of the given element which is under the given point in screen coodinates.
  873. Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_element, Element* element) const
  874. {
  875. if (element == nullptr)
  876. {
  877. if (ignore_element == root.get())
  878. return nullptr;
  879. element = root.get();
  880. }
  881. // Check if any documents have modal focus; if so, only check down than document.
  882. if (element == root.get())
  883. {
  884. if (focus)
  885. {
  886. ElementDocument* focus_document = focus->GetOwnerDocument();
  887. if (focus_document != nullptr &&
  888. focus_document->IsModal())
  889. {
  890. element = focus_document;
  891. }
  892. }
  893. }
  894. // Check any elements within our stacking context. We want to return the lowest-down element
  895. // that is under the cursor.
  896. if (element->local_stacking_context)
  897. {
  898. if (element->stacking_context_dirty)
  899. element->BuildLocalStackingContext();
  900. for (int i = (int) element->stacking_context.size() - 1; i >= 0; --i)
  901. {
  902. if (ignore_element != nullptr)
  903. {
  904. Element* element_hierarchy = element->stacking_context[i];
  905. while (element_hierarchy != nullptr)
  906. {
  907. if (element_hierarchy == ignore_element)
  908. break;
  909. element_hierarchy = element_hierarchy->GetParentNode();
  910. }
  911. if (element_hierarchy != nullptr)
  912. continue;
  913. }
  914. Element* child_element = GetElementAtPoint(point, ignore_element, element->stacking_context[i]);
  915. if (child_element != nullptr)
  916. return child_element;
  917. }
  918. }
  919. // Ignore elements whose pointer events are disabled.
  920. if (element->GetComputedValues().pointer_events == Style::PointerEvents::None)
  921. return nullptr;
  922. // Projection may fail if we have a singular transformation matrix.
  923. bool projection_result = element->Project(point);
  924. // Check if the point is actually within this element.
  925. bool within_element = (projection_result && element->IsPointWithinElement(point));
  926. if (within_element)
  927. {
  928. Vector2i clip_origin, clip_dimensions;
  929. if (ElementUtilities::GetClippingRegion(clip_origin, clip_dimensions, element))
  930. {
  931. within_element = point.x >= clip_origin.x &&
  932. point.y >= clip_origin.y &&
  933. point.x <= (clip_origin.x + clip_dimensions.x) &&
  934. point.y <= (clip_origin.y + clip_dimensions.y);
  935. }
  936. }
  937. if (within_element)
  938. return element;
  939. return nullptr;
  940. }
  941. // Creates the drag clone from the given element.
  942. void Context::CreateDragClone(Element* element)
  943. {
  944. if (!cursor_proxy)
  945. {
  946. Log::Message(Log::LT_ERROR, "Unable to create drag clone, no cursor proxy document.");
  947. return;
  948. }
  949. ReleaseDragClone();
  950. // Instance the drag clone.
  951. ElementPtr element_drag_clone = element->Clone();
  952. if (!element_drag_clone)
  953. {
  954. Log::Message(Log::LT_ERROR, "Unable to duplicate drag clone.");
  955. return;
  956. }
  957. drag_clone = element_drag_clone.get();
  958. // Append the clone to the cursor proxy element.
  959. cursor_proxy->AppendChild(std::move(element_drag_clone));
  960. // Set the style sheet on the cursor proxy.
  961. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheet(element->GetStyleSheet());
  962. // Set all the required properties and pseudo-classes on the clone.
  963. drag_clone->SetPseudoClass("drag", true);
  964. drag_clone->SetProperty(PropertyId::Position, Property(Style::Position::Absolute));
  965. drag_clone->SetProperty(PropertyId::Left, Property(element->GetAbsoluteLeft() - element->GetBox().GetEdge(Box::MARGIN, Box::LEFT) - mouse_position.x, Property::PX));
  966. drag_clone->SetProperty(PropertyId::Top, Property(element->GetAbsoluteTop() - element->GetBox().GetEdge(Box::MARGIN, Box::TOP) - mouse_position.y, Property::PX));
  967. }
  968. // Releases the drag clone, if one exists.
  969. void Context::ReleaseDragClone()
  970. {
  971. if (drag_clone)
  972. {
  973. cursor_proxy->RemoveChild(drag_clone);
  974. drag_clone = nullptr;
  975. }
  976. }
  977. DataModel* Context::GetDataModelPtr(const String& name) const
  978. {
  979. auto it = data_models.find(name);
  980. if (it != data_models.end())
  981. return it->second.get();
  982. return nullptr;
  983. }
  984. // Builds the parameters for a generic key event.
  985. void Context::GenerateKeyEventParameters(Dictionary& parameters, Input::KeyIdentifier key_identifier)
  986. {
  987. parameters["key_identifier"] = (int)key_identifier;
  988. }
  989. // Builds the parameters for a generic mouse event.
  990. void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_index)
  991. {
  992. parameters.reserve(3);
  993. parameters["mouse_x"] = mouse_position.x;
  994. parameters["mouse_y"] = mouse_position.y;
  995. if (button_index >= 0)
  996. parameters["button"] = button_index;
  997. }
  998. // Builds the parameters for the key modifier state.
  999. void Context::GenerateKeyModifierEventParameters(Dictionary& parameters, int key_modifier_state)
  1000. {
  1001. static const String property_names[] = {
  1002. "ctrl_key",
  1003. "shift_key",
  1004. "alt_key",
  1005. "meta_key",
  1006. "caps_lock_key",
  1007. "num_lock_key",
  1008. "scroll_lock_key"
  1009. };
  1010. for (int i = 0; i < 7; i++)
  1011. parameters[property_names[i]] = (int)((key_modifier_state & (1 << i)) > 0);
  1012. }
  1013. // Builds the parameters for a drag event.
  1014. void Context::GenerateDragEventParameters(Dictionary& parameters)
  1015. {
  1016. parameters["drag_element"] = (void*)drag;
  1017. }
  1018. // Releases all unloaded documents pending destruction.
  1019. void Context::ReleaseUnloadedDocuments()
  1020. {
  1021. if (!unloaded_documents.empty())
  1022. {
  1023. OwnedElementList documents = std::move(unloaded_documents);
  1024. unloaded_documents.clear();
  1025. // Clear the deleted list.
  1026. for (size_t i = 0; i < documents.size(); ++i)
  1027. documents[i]->GetEventDispatcher()->DetachAllEvents();
  1028. documents.clear();
  1029. }
  1030. }
  1031. using ElementObserverList = Vector< ObserverPtr<Element> >;
  1032. class ElementObserverListBackInserter {
  1033. public:
  1034. using iterator_category = std::output_iterator_tag;
  1035. using value_type = void;
  1036. using difference_type = void;
  1037. using pointer = void;
  1038. using reference = void;
  1039. using container_type = ElementObserverList;
  1040. ElementObserverListBackInserter(ElementObserverList& elements) : elements(&elements) {}
  1041. ElementObserverListBackInserter& operator=(const Element* element) {
  1042. elements->push_back(element->GetObserverPtr());
  1043. return *this;
  1044. }
  1045. ElementObserverListBackInserter& operator*() { return *this; }
  1046. ElementObserverListBackInserter& operator++() { return *this; }
  1047. ElementObserverListBackInserter& operator++(int) { return *this; }
  1048. private:
  1049. ElementObserverList* elements;
  1050. };
  1051. // Sends the specified event to all elements in new_items that don't appear in old_items.
  1052. void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, EventId id, const Dictionary& parameters)
  1053. {
  1054. // We put our elements in observer pointers in case some of them are deleted during dispatch.
  1055. ElementObserverList elements;
  1056. std::set_difference(old_items.begin(), old_items.end(), new_items.begin(), new_items.end(), ElementObserverListBackInserter(elements));
  1057. for (auto& element : elements)
  1058. {
  1059. if (element)
  1060. element->DispatchEvent(id, parameters);
  1061. }
  1062. }
  1063. void Context::Release()
  1064. {
  1065. if (instancer)
  1066. {
  1067. instancer->ReleaseContext(this);
  1068. }
  1069. }
  1070. void Context::SetDocumentsBaseTag(const String& tag)
  1071. {
  1072. documents_base_tag = tag;
  1073. }
  1074. const String& Context::GetDocumentsBaseTag()
  1075. {
  1076. return documents_base_tag;
  1077. }
  1078. } // namespace Rml