Context.cpp 35 KB

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