Context.cpp 33 KB

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