Context.cpp 36 KB

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