Context.cpp 37 KB

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