Context.cpp 37 KB

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