Context.cpp 33 KB

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