Context.cpp 33 KB

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