Context.cpp 37 KB

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