Context.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  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. bool Context::ProcessTextInput(char character)
  408. {
  409. // Only the standard ASCII character set is a valid subset of UTF-8.
  410. if (character < 0 || character > 127)
  411. return false;
  412. return ProcessTextInput(static_cast<Character>(character));
  413. }
  414. // Sends a single character of text as text input into RmlUi.
  415. bool Context::ProcessTextInput(Character character)
  416. {
  417. // Generate the parameters for the key event.
  418. String text = StringUtilities::ToUTF8(character);
  419. return ProcessTextInput(text);
  420. }
  421. // Sends a string of text as text input into RmlUi.
  422. bool Context::ProcessTextInput(const String& string)
  423. {
  424. Element* target = (focus ? focus : root.get());
  425. Dictionary parameters;
  426. parameters["text"] = string;
  427. bool consumed = target->DispatchEvent(EventId::Textinput, parameters);
  428. return consumed;
  429. }
  430. // Sends a mouse movement event into RmlUi.
  431. void Context::ProcessMouseMove(int x, int y, int key_modifier_state)
  432. {
  433. // Check whether the mouse moved since the last event came through.
  434. Vector2i old_mouse_position = mouse_position;
  435. bool mouse_moved = (x != mouse_position.x) || (y != mouse_position.y);
  436. if (mouse_moved)
  437. {
  438. mouse_position.x = x;
  439. mouse_position.y = y;
  440. }
  441. // Generate the parameters for the mouse events (there could be a few!).
  442. Dictionary parameters;
  443. GenerateMouseEventParameters(parameters, -1);
  444. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  445. Dictionary drag_parameters;
  446. GenerateMouseEventParameters(drag_parameters);
  447. GenerateDragEventParameters(drag_parameters);
  448. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  449. // Update the current hover chain. This will send all necessary 'onmouseout', 'onmouseover', 'ondragout' and
  450. // 'ondragover' messages.
  451. UpdateHoverChain(parameters, drag_parameters, old_mouse_position);
  452. // Dispatch any 'onmousemove' events.
  453. if (mouse_moved)
  454. {
  455. if (hover)
  456. {
  457. hover->DispatchEvent(EventId::Mousemove, parameters);
  458. if (drag_hover &&
  459. drag_verbose)
  460. drag_hover->DispatchEvent(EventId::Dragmove, drag_parameters);
  461. }
  462. }
  463. }
  464. static Element* FindFocusElement(Element* element)
  465. {
  466. ElementDocument* owner_document = element->GetOwnerDocument();
  467. if (!owner_document || owner_document->GetComputedValues().focus == Style::Focus::None)
  468. return nullptr;
  469. while (element && element->GetComputedValues().focus == Style::Focus::None)
  470. {
  471. element = element->GetParentNode();
  472. }
  473. return element;
  474. }
  475. // Sends a mouse-button down event into RmlUi.
  476. void Context::ProcessMouseButtonDown(int button_index, int key_modifier_state)
  477. {
  478. Dictionary parameters;
  479. GenerateMouseEventParameters(parameters, button_index);
  480. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  481. if (button_index == 0)
  482. {
  483. Element* new_focus = hover;
  484. // Set the currently hovered element to focus if it isn't already the focus.
  485. if (hover)
  486. {
  487. new_focus = FindFocusElement(hover);
  488. if (new_focus && new_focus != focus)
  489. {
  490. if (!new_focus->Focus())
  491. return;
  492. }
  493. }
  494. // Save the just-pressed-on element as the pressed element.
  495. active = new_focus;
  496. bool propagate = true;
  497. // Call 'onmousedown' on every item in the hover chain, and copy the hover chain to the active chain.
  498. if (hover)
  499. propagate = hover->DispatchEvent(EventId::Mousedown, parameters);
  500. if (propagate)
  501. {
  502. // Check for a double-click on an element; if one has occured, we send the 'dblclick' event to the hover
  503. // element. If not, we'll start a timer to catch the next one.
  504. double click_time = GetSystemInterface()->GetElapsedTime();
  505. if (active == last_click_element &&
  506. float(click_time - last_click_time) < DOUBLE_CLICK_TIME)
  507. {
  508. if (hover)
  509. propagate = hover->DispatchEvent(EventId::Dblclick, parameters);
  510. last_click_element = nullptr;
  511. last_click_time = 0;
  512. }
  513. else
  514. {
  515. last_click_element = active;
  516. last_click_time = click_time;
  517. }
  518. }
  519. for (ElementSet::iterator itr = hover_chain.begin(); itr != hover_chain.end(); ++itr)
  520. active_chain.push_back((*itr));
  521. if (propagate)
  522. {
  523. // Traverse down the hierarchy of the newly focussed element (if any), and see if we can begin dragging it.
  524. drag_started = false;
  525. drag = hover;
  526. while (drag)
  527. {
  528. Style::Drag drag_style = drag->GetComputedValues().drag;
  529. switch (drag_style)
  530. {
  531. case Style::Drag::None: drag = drag->GetParentNode(); continue;
  532. case Style::Drag::Block: drag = nullptr; continue;
  533. default: drag_verbose = (drag_style == Style::Drag::DragDrop || drag_style == Style::Drag::Clone);
  534. }
  535. break;
  536. }
  537. }
  538. }
  539. else
  540. {
  541. // Not the primary mouse button, so we're not doing any special processing.
  542. if (hover)
  543. hover->DispatchEvent(EventId::Mousedown, parameters);
  544. }
  545. }
  546. // Sends a mouse-button up event into RmlUi.
  547. void Context::ProcessMouseButtonUp(int button_index, int key_modifier_state)
  548. {
  549. Dictionary parameters;
  550. GenerateMouseEventParameters(parameters, button_index);
  551. GenerateKeyModifierEventParameters(parameters, key_modifier_state);
  552. // Process primary click.
  553. if (button_index == 0)
  554. {
  555. // The elements in the new hover chain have the 'onmouseup' event called on them.
  556. if (hover)
  557. hover->DispatchEvent(EventId::Mouseup, parameters);
  558. // If the active element (the one that was being hovered over when the mouse button was pressed) is still being
  559. // hovered over, we click it.
  560. if (hover && active && active == FindFocusElement(hover))
  561. {
  562. active->DispatchEvent(EventId::Click, parameters);
  563. }
  564. // Unset the 'active' pseudo-class on all the elements in the active chain; because they may not necessarily
  565. // have had 'onmouseup' called on them, we can't guarantee this has happened already.
  566. auto func = PseudoClassFunctor("active", false);
  567. std::for_each(active_chain.begin(), active_chain.end(), func);
  568. active_chain.clear();
  569. if (drag)
  570. {
  571. if (drag_started)
  572. {
  573. Dictionary drag_parameters;
  574. GenerateMouseEventParameters(drag_parameters);
  575. GenerateDragEventParameters(drag_parameters);
  576. GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
  577. if (drag_hover)
  578. {
  579. if (drag_verbose)
  580. {
  581. drag_hover->DispatchEvent(EventId::Dragdrop, drag_parameters);
  582. // User may have removed the element, do an extra check.
  583. if(drag_hover)
  584. drag_hover->DispatchEvent(EventId::Dragout, drag_parameters);
  585. }
  586. }
  587. if(drag)
  588. drag->DispatchEvent(EventId::Dragend, drag_parameters);
  589. ReleaseDragClone();
  590. }
  591. drag = nullptr;
  592. drag_hover = nullptr;
  593. drag_hover_chain.clear();
  594. // We may have changes under our mouse, this ensures that the hover chain is properly updated
  595. ProcessMouseMove(mouse_position.x, mouse_position.y, key_modifier_state);
  596. }
  597. }
  598. else
  599. {
  600. // Not the left mouse button, so we're not doing any special processing.
  601. if (hover)
  602. hover->DispatchEvent(EventId::Mouseup, parameters);
  603. }
  604. }
  605. // Sends a mouse-wheel movement event into RmlUi.
  606. bool Context::ProcessMouseWheel(float wheel_delta, int key_modifier_state)
  607. {
  608. if (hover)
  609. {
  610. Dictionary scroll_parameters;
  611. GenerateKeyModifierEventParameters(scroll_parameters, key_modifier_state);
  612. scroll_parameters["wheel_delta"] = wheel_delta;
  613. return hover->DispatchEvent(EventId::Mousescroll, scroll_parameters);
  614. }
  615. return true;
  616. }
  617. // Gets the context's render interface.
  618. RenderInterface* Context::GetRenderInterface() const
  619. {
  620. return render_interface;
  621. }
  622. // Gets the current clipping region for the render traversal
  623. bool Context::GetActiveClipRegion(Vector2i& origin, Vector2i& dimensions) const
  624. {
  625. if (clip_dimensions.x < 0 || clip_dimensions.y < 0)
  626. return false;
  627. origin = clip_origin;
  628. dimensions = clip_dimensions;
  629. return true;
  630. }
  631. // Sets the current clipping region for the render traversal
  632. void Context::SetActiveClipRegion(const Vector2i& origin, const Vector2i& dimensions)
  633. {
  634. clip_origin = origin;
  635. clip_dimensions = dimensions;
  636. }
  637. // Sets the instancer to use for releasing this object.
  638. void Context::SetInstancer(ContextInstancer* _instancer)
  639. {
  640. RMLUI_ASSERT(instancer == nullptr);
  641. instancer = _instancer;
  642. }
  643. // Internal callback for when an element is removed from the hierarchy.
  644. void Context::OnElementDetach(Element* element)
  645. {
  646. auto it_hover = hover_chain.find(element);
  647. if (it_hover != hover_chain.end())
  648. {
  649. Dictionary parameters;
  650. GenerateMouseEventParameters(parameters, -1);
  651. element->DispatchEvent(EventId::Mouseout, parameters);
  652. hover_chain.erase(it_hover);
  653. if (hover == element)
  654. hover = nullptr;
  655. }
  656. auto it_active = std::find(active_chain.begin(), active_chain.end(), element);
  657. if (it_active != active_chain.end())
  658. {
  659. active_chain.erase(it_active);
  660. if (active == element)
  661. active = nullptr;
  662. }
  663. if (drag)
  664. {
  665. auto it = drag_hover_chain.find(element);
  666. if (it != drag_hover_chain.end())
  667. {
  668. drag_hover_chain.erase(it);
  669. if (drag_hover == element)
  670. drag_hover = nullptr;
  671. }
  672. if (drag == element)
  673. {
  674. // The dragged element is being removed, silently cancel the drag operation
  675. if (drag_started)
  676. ReleaseDragClone();
  677. drag = nullptr;
  678. drag_hover = nullptr;
  679. drag_hover_chain.clear();
  680. }
  681. }
  682. // Focus normally cleared and set by parent during Element::RemoveChild.
  683. // However, there are some exceptions, such as when an there are multiple
  684. // ElementDocuments in the hierarchy above the current element.
  685. if (element == focus)
  686. focus = nullptr;
  687. // If the element is a document lower down in the hierarchy, we may need to remove it from the focus history.
  688. if (element->GetOwnerDocument() == element)
  689. {
  690. auto it = std::find(document_focus_history.begin(), document_focus_history.end(), element);
  691. if (it != document_focus_history.end())
  692. document_focus_history.erase(it);
  693. }
  694. }
  695. // Internal callback for when a new element gains focus
  696. bool Context::OnFocusChange(Element* new_focus)
  697. {
  698. RMLUI_ASSERT(new_focus);
  699. ElementSet old_chain;
  700. ElementSet new_chain;
  701. Element* old_focus = focus;
  702. ElementDocument* old_document = old_focus ? old_focus->GetOwnerDocument() : nullptr;
  703. ElementDocument* new_document = new_focus->GetOwnerDocument();
  704. // If the current focus is modal and the new focus is not modal, deny the request
  705. if (old_document && old_document->IsModal() && (!new_document || !new_document->GetOwnerDocument()->IsModal()))
  706. return false;
  707. // Build the old chains
  708. Element* element = old_focus;
  709. while (element)
  710. {
  711. old_chain.insert(element);
  712. element = element->GetParentNode();
  713. }
  714. // Build the new chain
  715. element = new_focus;
  716. while (element)
  717. {
  718. new_chain.insert(element);
  719. element = element->GetParentNode();
  720. }
  721. Dictionary parameters;
  722. // Send out blur/focus events.
  723. SendEvents(old_chain, new_chain, EventId::Blur, parameters);
  724. SendEvents(new_chain, old_chain, EventId::Focus, parameters);
  725. focus = new_focus;
  726. // Raise the element's document to the front, if desired.
  727. ElementDocument* document = focus->GetOwnerDocument();
  728. if (document != nullptr)
  729. {
  730. Style::ZIndex z_index_property = document->GetComputedValues().z_index;
  731. if (z_index_property.type == Style::ZIndex::Auto)
  732. document->PullToFront();
  733. }
  734. // Update the focus history
  735. if (old_document != new_document)
  736. {
  737. // If documents have changed, add the new document to the end of the history
  738. ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), new_document);
  739. if (itr != document_focus_history.end())
  740. document_focus_history.erase(itr);
  741. if (new_document != nullptr)
  742. document_focus_history.push_back(new_document);
  743. }
  744. return true;
  745. }
  746. // Generates an event for faking clicks on an element.
  747. void Context::GenerateClickEvent(Element* element)
  748. {
  749. Dictionary parameters;
  750. GenerateMouseEventParameters(parameters, 0);
  751. element->DispatchEvent(EventId::Click, parameters);
  752. }
  753. // Updates the current hover elements, sending required events.
  754. void Context::UpdateHoverChain(const Dictionary& parameters, const Dictionary& drag_parameters, const Vector2i& old_mouse_position)
  755. {
  756. Vector2f position((float) mouse_position.x, (float) mouse_position.y);
  757. // Send out drag events.
  758. if (drag)
  759. {
  760. if (mouse_position != old_mouse_position)
  761. {
  762. if (!drag_started)
  763. {
  764. Dictionary drag_start_parameters = drag_parameters;
  765. drag_start_parameters["mouse_x"] = old_mouse_position.x;
  766. drag_start_parameters["mouse_y"] = old_mouse_position.y;
  767. drag->DispatchEvent(EventId::Dragstart, drag_start_parameters);
  768. drag_started = true;
  769. if (drag->GetComputedValues().drag == Style::Drag::Clone)
  770. {
  771. // Clone the element and attach it to the mouse cursor.
  772. CreateDragClone(drag);
  773. }
  774. }
  775. drag->DispatchEvent(EventId::Drag, drag_parameters);
  776. }
  777. }
  778. hover = GetElementAtPoint(position);
  779. if(enable_cursor)
  780. {
  781. String new_cursor_name;
  782. if(drag)
  783. new_cursor_name = drag->GetComputedValues().cursor;
  784. else if (hover)
  785. new_cursor_name = hover->GetComputedValues().cursor;
  786. if(new_cursor_name != cursor_name)
  787. {
  788. GetSystemInterface()->SetMouseCursor(new_cursor_name);
  789. cursor_name = new_cursor_name;
  790. }
  791. }
  792. // Build the new hover chain.
  793. ElementSet new_hover_chain;
  794. Element* element = hover;
  795. while (element != nullptr)
  796. {
  797. new_hover_chain.insert(element);
  798. element = element->GetParentNode();
  799. }
  800. // Send mouseout / mouseover events.
  801. SendEvents(hover_chain, new_hover_chain, EventId::Mouseout, parameters);
  802. SendEvents(new_hover_chain, hover_chain, EventId::Mouseover, parameters);
  803. // Send out drag events.
  804. if (drag)
  805. {
  806. drag_hover = GetElementAtPoint(position, drag);
  807. ElementSet new_drag_hover_chain;
  808. element = drag_hover;
  809. while (element != nullptr)
  810. {
  811. new_drag_hover_chain.insert(element);
  812. element = element->GetParentNode();
  813. }
  814. if (drag_started &&
  815. drag_verbose)
  816. {
  817. // Send out ondragover and ondragout events as appropriate.
  818. SendEvents(drag_hover_chain, new_drag_hover_chain, EventId::Dragout, drag_parameters);
  819. SendEvents(new_drag_hover_chain, drag_hover_chain, EventId::Dragover, drag_parameters);
  820. }
  821. drag_hover_chain.swap(new_drag_hover_chain);
  822. }
  823. // Swap the new chain in.
  824. hover_chain.swap(new_hover_chain);
  825. }
  826. // Returns the youngest descendent of the given element which is under the given point in screen coodinates.
  827. Element* Context::GetElementAtPoint(Vector2f point, const Element* ignore_element, Element* element) const
  828. {
  829. if (element == nullptr)
  830. {
  831. if (ignore_element == root.get())
  832. return nullptr;
  833. element = root.get();
  834. }
  835. // Check if any documents have modal focus; if so, only check down than document.
  836. if (element == root.get())
  837. {
  838. if (focus)
  839. {
  840. ElementDocument* focus_document = focus->GetOwnerDocument();
  841. if (focus_document != nullptr &&
  842. focus_document->IsModal())
  843. {
  844. element = focus_document;
  845. }
  846. }
  847. }
  848. // Check any elements within our stacking context. We want to return the lowest-down element
  849. // that is under the cursor.
  850. if (element->local_stacking_context)
  851. {
  852. if (element->stacking_context_dirty)
  853. element->BuildLocalStackingContext();
  854. for (int i = (int) element->stacking_context.size() - 1; i >= 0; --i)
  855. {
  856. if (ignore_element != nullptr)
  857. {
  858. Element* element_hierarchy = element->stacking_context[i];
  859. while (element_hierarchy != nullptr)
  860. {
  861. if (element_hierarchy == ignore_element)
  862. break;
  863. element_hierarchy = element_hierarchy->GetParentNode();
  864. }
  865. if (element_hierarchy != nullptr)
  866. continue;
  867. }
  868. Element* child_element = GetElementAtPoint(point, ignore_element, element->stacking_context[i]);
  869. if (child_element != nullptr)
  870. return child_element;
  871. }
  872. }
  873. // Ignore elements whose pointer events are disabled.
  874. if (element->GetComputedValues().pointer_events == Style::PointerEvents::None)
  875. return nullptr;
  876. // Projection may fail if we have a singular transformation matrix.
  877. bool projection_result = element->Project(point);
  878. // Check if the point is actually within this element.
  879. bool within_element = (projection_result && element->IsPointWithinElement(point));
  880. if (within_element)
  881. {
  882. Vector2i clip_origin, clip_dimensions;
  883. if (ElementUtilities::GetClippingRegion(clip_origin, clip_dimensions, element))
  884. {
  885. within_element = point.x >= clip_origin.x &&
  886. point.y >= clip_origin.y &&
  887. point.x <= (clip_origin.x + clip_dimensions.x) &&
  888. point.y <= (clip_origin.y + clip_dimensions.y);
  889. }
  890. }
  891. if (within_element)
  892. return element;
  893. return nullptr;
  894. }
  895. // Creates the drag clone from the given element.
  896. void Context::CreateDragClone(Element* element)
  897. {
  898. if (!cursor_proxy)
  899. {
  900. Log::Message(Log::LT_ERROR, "Unable to create drag clone, no cursor proxy document.");
  901. return;
  902. }
  903. ReleaseDragClone();
  904. // Instance the drag clone.
  905. ElementPtr element_drag_clone = element->Clone();
  906. if (!element_drag_clone)
  907. {
  908. Log::Message(Log::LT_ERROR, "Unable to duplicate drag clone.");
  909. return;
  910. }
  911. drag_clone = element_drag_clone.get();
  912. // Append the clone to the cursor proxy element.
  913. cursor_proxy->AppendChild(std::move(element_drag_clone));
  914. // Set the style sheet on the cursor proxy.
  915. static_cast<ElementDocument&>(*cursor_proxy).SetStyleSheet(element->GetStyleSheet());
  916. // Set all the required properties and pseudo-classes on the clone.
  917. drag_clone->SetPseudoClass("drag", true);
  918. drag_clone->SetProperty(PropertyId::Position, Property(Style::Position::Absolute));
  919. drag_clone->SetProperty(PropertyId::Left, Property(element->GetAbsoluteLeft() - element->GetBox().GetEdge(Box::MARGIN, Box::LEFT) - mouse_position.x, Property::PX));
  920. drag_clone->SetProperty(PropertyId::Top, Property(element->GetAbsoluteTop() - element->GetBox().GetEdge(Box::MARGIN, Box::TOP) - mouse_position.y, Property::PX));
  921. }
  922. // Releases the drag clone, if one exists.
  923. void Context::ReleaseDragClone()
  924. {
  925. if (drag_clone)
  926. {
  927. cursor_proxy->RemoveChild(drag_clone);
  928. drag_clone = nullptr;
  929. }
  930. }
  931. // Builds the parameters for a generic key event.
  932. void Context::GenerateKeyEventParameters(Dictionary& parameters, Input::KeyIdentifier key_identifier)
  933. {
  934. parameters["key_identifier"] = (int)key_identifier;
  935. }
  936. // Builds the parameters for a generic mouse event.
  937. void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_index)
  938. {
  939. parameters.reserve(3);
  940. parameters["mouse_x"] = mouse_position.x;
  941. parameters["mouse_y"] = mouse_position.y;
  942. if (button_index >= 0)
  943. parameters["button"] = button_index;
  944. }
  945. // Builds the parameters for the key modifier state.
  946. void Context::GenerateKeyModifierEventParameters(Dictionary& parameters, int key_modifier_state)
  947. {
  948. static const String property_names[] = {
  949. "ctrl_key",
  950. "shift_key",
  951. "alt_key",
  952. "meta_key",
  953. "caps_lock_key",
  954. "num_lock_key",
  955. "scroll_lock_key"
  956. };
  957. for (int i = 0; i < 7; i++)
  958. parameters[property_names[i]] = (int)((key_modifier_state & (1 << i)) > 0);
  959. }
  960. // Builds the parameters for a drag event.
  961. void Context::GenerateDragEventParameters(Dictionary& parameters)
  962. {
  963. parameters["drag_element"] = (void*)drag;
  964. }
  965. // Releases all unloaded documents pending destruction.
  966. void Context::ReleaseUnloadedDocuments()
  967. {
  968. if (!unloaded_documents.empty())
  969. {
  970. OwnedElementList documents = std::move(unloaded_documents);
  971. unloaded_documents.clear();
  972. // Clear the deleted list.
  973. for (size_t i = 0; i < documents.size(); ++i)
  974. documents[i]->GetEventDispatcher()->DetachAllEvents();
  975. documents.clear();
  976. }
  977. }
  978. using ElementObserverList = std::vector< ObserverPtr<Element> >;
  979. class ElementObserverListBackInserter {
  980. public:
  981. using iterator_category = std::output_iterator_tag;
  982. using value_type = void;
  983. using difference_type = void;
  984. using pointer = void;
  985. using reference = void;
  986. using container_type = ElementObserverList;
  987. ElementObserverListBackInserter(ElementObserverList& elements) : elements(&elements) {}
  988. ElementObserverListBackInserter& operator=(const Element* element) {
  989. elements->push_back(element->GetObserverPtr());
  990. return *this;
  991. }
  992. ElementObserverListBackInserter& operator*() { return *this; }
  993. ElementObserverListBackInserter& operator++() { return *this; }
  994. ElementObserverListBackInserter& operator++(int) { return *this; }
  995. private:
  996. ElementObserverList* elements;
  997. };
  998. // Sends the specified event to all elements in new_items that don't appear in old_items.
  999. void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, EventId id, const Dictionary& parameters)
  1000. {
  1001. // We put our elements in observer pointers in case some of them are deleted during dispatch.
  1002. ElementObserverList elements;
  1003. std::set_difference(old_items.begin(), old_items.end(), new_items.begin(), new_items.end(), ElementObserverListBackInserter(elements));
  1004. for (auto& element : elements)
  1005. {
  1006. if (element)
  1007. element->DispatchEvent(id, parameters);
  1008. }
  1009. }
  1010. void Context::Release()
  1011. {
  1012. if (instancer)
  1013. {
  1014. instancer->ReleaseContext(this);
  1015. }
  1016. }
  1017. }
  1018. }