Context.cpp 34 KB

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