Context.cpp 35 KB

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