Context.cpp 33 KB

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