Context.cpp 35 KB

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