Context.cpp 33 KB

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