Context.cpp 32 KB

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