Context.cpp 33 KB

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