Context.cpp 33 KB

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