Context.cpp 34 KB

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