Context.cpp 32 KB

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