Context.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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 "precompiled.h"
  29. #include "../../Include/RmlUi/Core.h"
  30. #include "EventDispatcher.h"
  31. #include "EventIterators.h"
  32. #include "PluginRegistry.h"
  33. #include "StreamFile.h"
  34. #include "../../Include/RmlUi/Core/StreamMemory.h"
  35. #include <algorithm>
  36. #include <iterator>
  37. namespace Rml {
  38. namespace Core {
  39. const float DOUBLE_CLICK_TIME = 0.5f;
  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 = 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. }
  68. Context::~Context()
  69. {
  70. PluginRegistry::NotifyContextDestroy(this);
  71. UnloadAllDocuments();
  72. ReleaseUnloadedDocuments();
  73. cursor_proxy.reset();
  74. root.reset();
  75. instancer = nullptr;
  76. render_interface = nullptr;
  77. }
  78. // Returns the name of the context.
  79. const String& Context::GetName() const
  80. {
  81. return name;
  82. }
  83. // Changes the dimensions of the screen.
  84. void Context::SetDimensions(const Vector2i& _dimensions)
  85. {
  86. if (dimensions != _dimensions)
  87. {
  88. dimensions = _dimensions;
  89. root->SetBox(Box(Vector2f((float) dimensions.x, (float) dimensions.y)));
  90. root->DirtyLayout();
  91. for (int i = 0; i < root->GetNumChildren(); ++i)
  92. {
  93. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  94. if (document != nullptr)
  95. {
  96. document->DirtyLayout();
  97. document->DirtyPosition();
  98. document->DispatchEvent(EventId::Resize, Dictionary());
  99. }
  100. }
  101. clip_dimensions = dimensions;
  102. }
  103. }
  104. // Returns the dimensions of the screen.
  105. const Vector2i& Context::GetDimensions() const
  106. {
  107. return dimensions;
  108. }
  109. void Context::SetDensityIndependentPixelRatio(float _density_independent_pixel_ratio)
  110. {
  111. if (density_independent_pixel_ratio != _density_independent_pixel_ratio)
  112. {
  113. density_independent_pixel_ratio = _density_independent_pixel_ratio;
  114. for (int i = 0; i < root->GetNumChildren(); ++i)
  115. {
  116. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  117. if (document != nullptr)
  118. {
  119. document->DirtyDpProperties();
  120. }
  121. }
  122. }
  123. }
  124. float Context::GetDensityIndependentPixelRatio() const
  125. {
  126. return density_independent_pixel_ratio;
  127. }
  128. // Updates all elements in the element tree.
  129. bool Context::Update()
  130. {
  131. RMLUI_ZoneScoped;
  132. root->Update(density_independent_pixel_ratio);
  133. for (int i = 0; i < root->GetNumChildren(); ++i)
  134. if (auto doc = root->GetChild(i)->GetOwnerDocument())
  135. {
  136. doc->UpdateLayout();
  137. doc->UpdatePosition();
  138. }
  139. // Release any documents that were unloaded during the update.
  140. ReleaseUnloadedDocuments();
  141. return true;
  142. }
  143. // Renders all visible elements in the element tree.
  144. bool Context::Render()
  145. {
  146. RMLUI_ZoneScoped;
  147. RenderInterface* render_interface = GetRenderInterface();
  148. if (render_interface == nullptr)
  149. return false;
  150. render_interface->context = this;
  151. ElementUtilities::ApplyActiveClipRegion(this, render_interface);
  152. root->Render();
  153. ElementUtilities::SetClippingRegion(nullptr, this);
  154. // Render the cursor proxy so any elements attached the cursor will be rendered below the cursor.
  155. if (cursor_proxy)
  156. {
  157. static_cast<ElementDocument&>(*cursor_proxy).UpdateDocument();
  158. cursor_proxy->SetOffset(Vector2f((float)Math::Clamp(mouse_position.x, 0, dimensions.x),
  159. (float)Math::Clamp(mouse_position.y, 0, dimensions.y)),
  160. nullptr);
  161. cursor_proxy->Render();
  162. }
  163. render_interface->context = nullptr;
  164. return true;
  165. }
  166. // Creates a new, empty document and places it into this context.
  167. ElementDocument* Context::CreateDocument(const String& tag)
  168. {
  169. ElementPtr element = Factory::InstanceElement(nullptr, tag, "body", XMLAttributes());
  170. if (!element)
  171. {
  172. Log::Message(Log::LT_ERROR, "Failed to instance document on tag '%s', instancer returned nullptr.", tag.c_str());
  173. return nullptr;
  174. }
  175. ElementDocument* document = dynamic_cast< ElementDocument* >(element.get());
  176. if (!document)
  177. {
  178. Log::Message(Log::LT_ERROR, "Failed to instance document on tag '%s', Found type '%s', was expecting derivative of ElementDocument.", tag.c_str(), typeid(element).name());
  179. return nullptr;
  180. }
  181. document->context = this;
  182. root->AppendChild(std::move(element));
  183. PluginRegistry::NotifyDocumentLoad(document);
  184. return document;
  185. }
  186. // Load a document into the context.
  187. ElementDocument* Context::LoadDocument(const String& document_path)
  188. {
  189. auto stream = std::make_unique<StreamFile>();
  190. if (!stream->Open(document_path))
  191. return nullptr;
  192. ElementDocument* document = LoadDocument(stream.get());
  193. return document;
  194. }
  195. // Load a document into the context.
  196. ElementDocument* Context::LoadDocument(Stream* stream)
  197. {
  198. PluginRegistry::NotifyDocumentOpen(this, stream->GetSourceURL().GetURL());
  199. ElementPtr element = Factory::InstanceDocumentStream(this, stream);
  200. if (!element)
  201. return nullptr;
  202. ElementDocument* document = static_cast<ElementDocument*>(element.get());
  203. root->AppendChild(std::move(element));
  204. ElementUtilities::BindEventAttributes(document);
  205. // The 'load' event is fired before updating the document, because the user might
  206. // need to initalize things before running an update. The drawback is that computed
  207. // values and layouting are not performed yet, resulting in default values when
  208. // querying such information in the event handler.
  209. PluginRegistry::NotifyDocumentLoad(document);
  210. document->DispatchEvent(EventId::Load, Dictionary());
  211. document->UpdateDocument();
  212. return document;
  213. }
  214. // Load a document into the context.
  215. ElementDocument* Context::LoadDocumentFromMemory(const String& string)
  216. {
  217. // Open the stream based on the string contents.
  218. auto stream = std::make_unique<StreamMemory>((byte*)string.c_str(), string.size());
  219. stream->SetSourceURL("[document from memory]");
  220. // Load the document from the stream.
  221. ElementDocument* document = LoadDocument(stream.get());
  222. return document;
  223. }
  224. // Unload the given document
  225. void Context::UnloadDocument(ElementDocument* _document)
  226. {
  227. // Has this document already been unloaded?
  228. for (size_t i = 0; i < unloaded_documents.size(); ++i)
  229. {
  230. if (unloaded_documents[i].get() == _document)
  231. return;
  232. }
  233. ElementDocument* document = _document;
  234. if (document->GetParentNode() == root.get())
  235. {
  236. // Dispatch the unload notifications.
  237. document->DispatchEvent(EventId::Unload, Dictionary());
  238. PluginRegistry::NotifyDocumentUnload(document);
  239. // Move document to a temporary location to be released later.
  240. unloaded_documents.push_back( root->RemoveChild(document) );
  241. }
  242. // Remove the item from the focus history.
  243. ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), document);
  244. if (itr != document_focus_history.end())
  245. document_focus_history.erase(itr);
  246. // Focus to the previous document if the old document is the current focus.
  247. if (focus && focus->GetOwnerDocument() == document)
  248. {
  249. focus = nullptr;
  250. document_focus_history.back()->GetFocusLeafNode()->Focus();
  251. }
  252. // Clear the active element if the old document is the active element.
  253. if (active && active->GetOwnerDocument() == document)
  254. {
  255. active = nullptr;
  256. }
  257. // Clear other pointers to elements whose owner was deleted
  258. if (drag && drag->GetOwnerDocument() == document)
  259. {
  260. drag = nullptr;
  261. }
  262. if (drag_hover && drag_hover->GetOwnerDocument() == document)
  263. {
  264. drag_hover = nullptr;
  265. }
  266. // Rebuild the hover state.
  267. UpdateHoverChain(Dictionary(), Dictionary(), mouse_position);
  268. }
  269. // Unload all the currently loaded documents
  270. void Context::UnloadAllDocuments()
  271. {
  272. // Unload all children.
  273. while (root->GetNumChildren(true) > 0)
  274. UnloadDocument(root->GetChild(0)->GetOwnerDocument());
  275. // The element lists may point to elements that are getting removed.
  276. active_chain.clear();
  277. hover_chain.clear();
  278. drag_hover_chain.clear();
  279. }
  280. // Enables or disables the mouse cursor.
  281. void Context::EnableMouseCursor(bool enable)
  282. {
  283. // The cursor is set to an invalid name so that it is forced to update in the next update loop.
  284. cursor_name = ":reset:";
  285. enable_cursor = enable;
  286. }
  287. // Returns the first document found in the root with the given id.
  288. ElementDocument* Context::GetDocument(const String& id)
  289. {
  290. for (int i = 0; i < root->GetNumChildren(); i++)
  291. {
  292. ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
  293. if (document == nullptr)
  294. continue;
  295. if (document->GetId() == id)
  296. return document;
  297. }
  298. return nullptr;
  299. }
  300. // Returns a document in the context by index.
  301. ElementDocument* Context::GetDocument(int index)
  302. {
  303. Element* element = root->GetChild(index);
  304. if (element == nullptr)
  305. return nullptr;
  306. return element->GetOwnerDocument();
  307. }
  308. // Returns the number of documents in the context.
  309. int Context::GetNumDocuments() const
  310. {
  311. return root->GetNumChildren();
  312. }
  313. // Returns the hover element.
  314. Element* Context::GetHoverElement()
  315. {
  316. return hover;
  317. }
  318. // Returns the focus element.
  319. Element* Context::GetFocusElement()
  320. {
  321. return focus;
  322. }
  323. // Returns the root element.
  324. Element* Context::GetRootElement()
  325. {
  326. return root.get();
  327. }
  328. // Brings the document to the front of the document stack.
  329. void Context::PullDocumentToFront(ElementDocument* document)
  330. {
  331. if (document != root->GetLastChild())
  332. {
  333. // Calling RemoveChild() / AppendChild() would be cleaner, but that dirties the document's layout
  334. // unnecessarily, so we'll go under the hood here.
  335. for (int i = 0; i < root->GetNumChildren(); ++i)
  336. {
  337. if (root->GetChild(i) == document)
  338. {
  339. ElementPtr element = std::move(root->children[i]);
  340. root->children.erase(root->children.begin() + i);
  341. root->children.insert(root->children.begin() + root->GetNumChildren(), std::move(element));
  342. root->DirtyStackingContext();
  343. }
  344. }
  345. }
  346. }
  347. // Sends the document to the back of the document stack.
  348. void Context::PushDocumentToBack(ElementDocument* document)
  349. {
  350. if (document != root->GetFirstChild())
  351. {
  352. // See PullDocumentToFront().
  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(), std::move(element));
  360. root->DirtyStackingContext();
  361. }
  362. }
  363. }
  364. }
  365. void Context::UnfocusDocument(ElementDocument* document)
  366. {
  367. auto it = std::find(document_focus_history.begin(), document_focus_history.end(), document);
  368. if (it != document_focus_history.end())
  369. document_focus_history.erase(it);
  370. if (!document_focus_history.empty())
  371. document_focus_history.back()->GetFocusLeafNode()->Focus();
  372. }
  373. // Adds an event listener to the root element.
  374. void Context::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  375. {
  376. root->AddEventListener(event, listener, in_capture_phase);
  377. }
  378. // Removes an event listener from the root element.
  379. void Context::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  380. {
  381. root->RemoveEventListener(event, listener, in_capture_phase);
  382. }
  383. // Sends a key down event into RmlUi.
  384. bool Context::ProcessKeyDown(Input::KeyIdentifier key_identifier, int key_modifier_state)
  385. {
  386. // Generate the parameters for the key event.
  387. Dictionary parameters;
  388. GenerateKeyEventParameters(parameters, key_identifier);
  389. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  390. if (focus)
  391. return focus->DispatchEvent(EventId::Keydown, parameters);
  392. else
  393. return root->DispatchEvent(EventId::Keydown, parameters);
  394. }
  395. // Sends a key up event into RmlUi.
  396. bool Context::ProcessKeyUp(Input::KeyIdentifier key_identifier, int key_modifier_state)
  397. {
  398. // Generate the parameters for the key event.
  399. Dictionary parameters;
  400. GenerateKeyEventParameters(parameters, key_identifier);
  401. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  402. if (focus)
  403. return focus->DispatchEvent(EventId::Keyup, parameters);
  404. else
  405. return root->DispatchEvent(EventId::Keyup, parameters);
  406. }
  407. // Sends a single character of text as text input into RmlUi.
  408. bool Context::ProcessTextInput(word character)
  409. {
  410. // Generate the parameters for the key event.
  411. Dictionary parameters;
  412. parameters["data"] = character;
  413. if (focus)
  414. return focus->DispatchEvent(EventId::Textinput, parameters);
  415. else
  416. return root->DispatchEvent(EventId::Textinput, parameters);
  417. }
  418. // Sends a string of text as text input into RmlUi.
  419. bool Context::ProcessTextInput(const String& string)
  420. {
  421. bool consumed = true;
  422. for (size_t i = 0; i < string.size(); ++i)
  423. {
  424. // Generate the parameters for the key event.
  425. Dictionary parameters;
  426. parameters["data"] = string[i];
  427. if (focus)
  428. consumed = focus->DispatchEvent(EventId::Textinput, parameters) && consumed;
  429. else
  430. consumed = root->DispatchEvent(EventId::Textinput, parameters) && consumed;
  431. }
  432. return consumed;
  433. }
  434. // Sends a mouse movement event into RmlUi.
  435. void Context::ProcessMouseMove(int x, int y, int key_modifier_state)
  436. {
  437. // Check whether the mouse moved since the last event came through.
  438. Vector2i old_mouse_position = mouse_position;
  439. bool mouse_moved = (x != mouse_position.x) || (y != mouse_position.y);
  440. if (mouse_moved)
  441. {
  442. mouse_position.x = x;
  443. mouse_position.y = y;
  444. }
  445. // Generate the parameters for the mouse events (there could be a few!).
  446. Dictionary parameters;
  447. GenerateMouseEventParameters(parameters, -1);
  448. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  449. Dictionary drag_parameters;
  450. GenerateMouseEventParameters(drag_parameters);
  451. GenerateDragEventParameters(drag_parameters);
  452. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  453. // Update the current hover chain. This will send all necessary 'onmouseout', 'onmouseover', 'ondragout' and
  454. // 'ondragover' messages.
  455. UpdateHoverChain(parameters, drag_parameters, old_mouse_position);
  456. // Dispatch any 'onmousemove' events.
  457. if (mouse_moved)
  458. {
  459. if (hover)
  460. {
  461. hover->DispatchEvent(EventId::Mousemove, parameters);
  462. if (drag_hover &&
  463. drag_verbose)
  464. drag_hover->DispatchEvent(EventId::Dragmove, drag_parameters);
  465. }
  466. }
  467. }
  468. static Element* FindFocusElement(Element* element)
  469. {
  470. ElementDocument* owner_document = element->GetOwnerDocument();
  471. if (!owner_document || owner_document->GetComputedValues().focus == Style::Focus::None)
  472. return nullptr;
  473. while (element && element->GetComputedValues().focus == Style::Focus::None)
  474. {
  475. element = element->GetParentNode();
  476. }
  477. return element;
  478. }
  479. // Sends a mouse-button down event into RmlUi.
  480. void Context::ProcessMouseButtonDown(int button_index, int key_modifier_state)
  481. {
  482. Dictionary parameters;
  483. GenerateMouseEventParameters(parameters, button_index);
  484. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  485. if (button_index == 0)
  486. {
  487. Element* new_focus = hover;
  488. // Set the currently hovered element to focus if it isn't already the focus.
  489. if (hover)
  490. {
  491. new_focus = FindFocusElement(hover);
  492. if (new_focus && new_focus != focus)
  493. {
  494. if (!new_focus->Focus())
  495. return;
  496. }
  497. }
  498. // Save the just-pressed-on element as the pressed element.
  499. active = new_focus;
  500. bool propogate = true;
  501. // Call 'onmousedown' on every item in the hover chain, and copy the hover chain to the active chain.
  502. if (hover)
  503. propogate = hover->DispatchEvent(EventId::Mousedown, parameters);
  504. if (propogate)
  505. {
  506. // Check for a double-click on an element; if one has occured, we send the 'dblclick' event to the hover
  507. // element. If not, we'll start a timer to catch the next one.
  508. double click_time = GetSystemInterface()->GetElapsedTime();
  509. if (active == last_click_element &&
  510. float(click_time - last_click_time) < DOUBLE_CLICK_TIME)
  511. {
  512. if (hover)
  513. propogate = 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. for (ElementSet::iterator itr = hover_chain.begin(); itr != hover_chain.end(); ++itr)
  524. active_chain.push_back((*itr));
  525. if (propogate)
  526. {
  527. // Traverse down the hierarchy of the newly focussed element (if any), and see if we can begin dragging it.
  528. drag_started = false;
  529. drag = hover;
  530. while (drag)
  531. {
  532. Style::Drag drag_style = drag->GetComputedValues().drag;
  533. switch (drag_style)
  534. {
  535. case Style::Drag::None: drag = drag->GetParentNode(); continue;
  536. case Style::Drag::Block: drag = nullptr; continue;
  537. default: drag_verbose = (drag_style == Style::Drag::DragDrop || drag_style == Style::Drag::Clone);
  538. }
  539. break;
  540. }
  541. }
  542. }
  543. else
  544. {
  545. // Not the primary mouse button, so we're not doing any special processing.
  546. if (hover)
  547. hover->DispatchEvent(EventId::Mousedown, parameters);
  548. }
  549. }
  550. // Sends a mouse-button up event into RmlUi.
  551. void Context::ProcessMouseButtonUp(int button_index, int key_modifier_state)
  552. {
  553. Dictionary parameters;
  554. GenerateMouseEventParameters(parameters, button_index);
  555. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  556. // Process primary click.
  557. if (button_index == 0)
  558. {
  559. // The elements in the new hover chain have the 'onmouseup' event called on them.
  560. if (hover)
  561. hover->DispatchEvent(EventId::Mouseup, parameters);
  562. // If the active element (the one that was being hovered over when the mouse button was pressed) is still being
  563. // hovered over, we click it.
  564. if (hover && active && active == FindFocusElement(hover))
  565. {
  566. active->DispatchEvent(EventId::Click, parameters);
  567. }
  568. // Unset the 'active' pseudo-class on all the elements in the active chain; because they may not necessarily
  569. // have had 'onmouseup' called on them, we can't guarantee this has happened already.
  570. auto func = PseudoClassFunctor("active", false);
  571. std::for_each(active_chain.begin(), active_chain.end(), func);
  572. active_chain.clear();
  573. if (drag)
  574. {
  575. if (drag_started)
  576. {
  577. Dictionary drag_parameters;
  578. GenerateMouseEventParameters(drag_parameters);
  579. GenerateDragEventParameters(drag_parameters);
  580. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  581. if (drag_hover)
  582. {
  583. if (drag_verbose)
  584. {
  585. drag_hover->DispatchEvent(EventId::Dragdrop, drag_parameters);
  586. // User may have removed the element, do an extra check.
  587. if(drag_hover)
  588. drag_hover->DispatchEvent(EventId::Dragout, drag_parameters);
  589. }
  590. }
  591. if(drag)
  592. drag->DispatchEvent(EventId::Dragend, drag_parameters);
  593. ReleaseDragClone();
  594. }
  595. drag = nullptr;
  596. drag_hover = nullptr;
  597. drag_hover_chain.clear();
  598. // We may have changes under our mouse, this ensures that the hover chain is properly updated
  599. ProcessMouseMove(mouse_position.x, mouse_position.y, key_modifier_state);
  600. }
  601. }
  602. else
  603. {
  604. // Not the left mouse button, so we're not doing any special processing.
  605. if (hover)
  606. hover->DispatchEvent(EventId::Mouseup, parameters);
  607. }
  608. }
  609. // Sends a mouse-wheel movement event into RmlUi.
  610. bool Context::ProcessMouseWheel(float wheel_delta, int key_modifier_state)
  611. {
  612. if (hover)
  613. {
  614. Dictionary scroll_parameters;
  615. GenerateKeyModifierEventParameters(scroll_parameters, key_modifier_state);
  616. scroll_parameters["wheel_delta"] = wheel_delta;
  617. return hover->DispatchEvent(EventId::Mousescroll, scroll_parameters);
  618. }
  619. return true;
  620. }
  621. // Gets the context's render interface.
  622. RenderInterface* Context::GetRenderInterface() const
  623. {
  624. return render_interface;
  625. }
  626. // Gets the current clipping region for the render traversal
  627. bool Context::GetActiveClipRegion(Vector2i& origin, Vector2i& dimensions) const
  628. {
  629. if (clip_dimensions.x < 0 || clip_dimensions.y < 0)
  630. return false;
  631. origin = clip_origin;
  632. dimensions = clip_dimensions;
  633. return true;
  634. }
  635. // Sets the current clipping region for the render traversal
  636. void Context::SetActiveClipRegion(const Vector2i& origin, const Vector2i& dimensions)
  637. {
  638. clip_origin = origin;
  639. clip_dimensions = dimensions;
  640. }
  641. // Sets the instancer to use for releasing this object.
  642. void Context::SetInstancer(ContextInstancer* _instancer)
  643. {
  644. RMLUI_ASSERT(instancer == nullptr);
  645. instancer = _instancer;
  646. }
  647. // Internal callback for when an element is removed from the hierarchy.
  648. void Context::OnElementDetach(Element* element)
  649. {
  650. auto it_hover = hover_chain.find(element);
  651. if (it_hover != hover_chain.end())
  652. {
  653. Dictionary parameters;
  654. GenerateMouseEventParameters(parameters, -1);
  655. RmlEventFunctor send_event(EventId::Mouseout, parameters);
  656. send_event(element);
  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 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. // Sends the specified event to all elements in new_items that don't appear in old_items.
  984. void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, EventId id, const Dictionary& parameters)
  985. {
  986. ElementList elements;
  987. std::set_difference(old_items.begin(), old_items.end(), new_items.begin(), new_items.end(), std::back_inserter(elements));
  988. RmlEventFunctor func(id, parameters);
  989. std::for_each(elements.begin(), elements.end(), func);
  990. }
  991. void Context::Release()
  992. {
  993. if (instancer)
  994. {
  995. instancer->ReleaseContext(this);
  996. }
  997. }
  998. }
  999. }