Context.cpp 37 KB

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