Context.cpp 32 KB

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