2
0

Context.cpp 33 KB

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