Context.cpp 32 KB

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