2
0

Context.cpp 37 KB

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