Context.cpp 32 KB

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