Context.cpp 33 KB

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