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