Context.cpp 33 KB

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