Context.cpp 37 KB

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