Context.cpp 33 KB

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