ElementDocument.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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/ElementDocument.h"
  29. #include "../../Include/Rocket/Core/StreamMemory.h"
  30. #include "../../Include/Rocket/Core.h"
  31. #include "DocumentHeader.h"
  32. #include "ElementStyle.h"
  33. #include "EventDispatcher.h"
  34. #include "LayoutEngine.h"
  35. #include "StreamFile.h"
  36. #include "StyleSheetFactory.h"
  37. #include "Template.h"
  38. #include "TemplateCache.h"
  39. #include "XMLParseTools.h"
  40. namespace Rocket {
  41. namespace Core {
  42. ElementDocument::ElementDocument(const String& tag) : Element(tag)
  43. {
  44. style_sheet = NULL;
  45. context = NULL;
  46. modal = false;
  47. layout_dirty = true;
  48. position_dirty = false;
  49. ForceLocalStackingContext();
  50. SetOwnerDocument(this);
  51. SetProperty(POSITION, Property(Style::Position::Absolute));
  52. }
  53. ElementDocument::~ElementDocument()
  54. {
  55. if (style_sheet != NULL)
  56. style_sheet->RemoveReference();
  57. }
  58. void ElementDocument::ProcessHeader(const DocumentHeader* document_header)
  59. {
  60. // Store the source address that we came from
  61. source_url = document_header->source;
  62. // Construct a new header and copy the template details across
  63. DocumentHeader header;
  64. header.MergePaths(header.template_resources, document_header->template_resources, document_header->source);
  65. // Merge in any templates, note a merge may cause more templates to merge
  66. for (size_t i = 0; i < header.template_resources.size(); i++)
  67. {
  68. Template* merge_template = TemplateCache::LoadTemplate(URL(header.template_resources[i]).GetURL());
  69. if (merge_template)
  70. header.MergeHeader(*merge_template->GetHeader());
  71. else
  72. Log::Message(Log::LT_WARNING, "Template %s not found", header.template_resources[i].c_str());
  73. }
  74. // Merge the document's header last, as it is the most overriding.
  75. header.MergeHeader(*document_header);
  76. // Set the title to the document title.
  77. title = document_header->title;
  78. // If a style-sheet (or sheets) has been specified for this element, then we load them and set the combined sheet
  79. // on the element; all of its children will inherit it by default.
  80. StyleSheet* style_sheet = NULL;
  81. if (header.rcss_external.size() > 0)
  82. style_sheet = StyleSheetFactory::GetStyleSheet(header.rcss_external);
  83. // Combine any inline sheets.
  84. if (header.rcss_inline.size() > 0)
  85. {
  86. for (size_t i = 0;i < header.rcss_inline.size(); i++)
  87. {
  88. StyleSheet* new_sheet = new StyleSheet();
  89. StreamMemory* stream = new StreamMemory((const byte*) header.rcss_inline[i].c_str(), header.rcss_inline[i].size());
  90. stream->SetSourceURL(document_header->source);
  91. if (new_sheet->LoadStyleSheet(stream))
  92. {
  93. if (style_sheet)
  94. {
  95. StyleSheet* combined_sheet = style_sheet->CombineStyleSheet(new_sheet);
  96. style_sheet->RemoveReference();
  97. new_sheet->RemoveReference();
  98. style_sheet = combined_sheet;
  99. }
  100. else
  101. style_sheet = new_sheet;
  102. }
  103. else
  104. new_sheet->RemoveReference();
  105. stream->RemoveReference();
  106. }
  107. }
  108. // If a style sheet is available, set it on the document and release it.
  109. if (style_sheet)
  110. {
  111. SetStyleSheet(style_sheet);
  112. style_sheet->RemoveReference();
  113. }
  114. // Load external scripts.
  115. for (size_t i = 0; i < header.scripts_external.size(); i++)
  116. {
  117. StreamFile* stream = new StreamFile();
  118. if (stream->Open(header.scripts_external[i]))
  119. LoadScript(stream, header.scripts_external[i]);
  120. stream->RemoveReference();
  121. }
  122. // Load internal scripts.
  123. for (size_t i = 0; i < header.scripts_inline.size(); i++)
  124. {
  125. StreamMemory* stream = new StreamMemory((const byte*) header.scripts_inline[i].c_str(), header.scripts_inline[i].size());
  126. LoadScript(stream, "");
  127. stream->RemoveReference();
  128. }
  129. // Hide this document.
  130. SetProperty(VISIBILITY, Property(Style::Visibility::Hidden));
  131. }
  132. // Returns the document's context.
  133. Context* ElementDocument::GetContext()
  134. {
  135. return context;
  136. }
  137. // Sets the document's title.
  138. void ElementDocument::SetTitle(const String& _title)
  139. {
  140. title = _title;
  141. }
  142. const String& ElementDocument::GetTitle() const
  143. {
  144. return title;
  145. }
  146. const String& ElementDocument::GetSourceURL() const
  147. {
  148. return source_url;
  149. }
  150. // Sets the style sheet this document, and all of its children, uses.
  151. void ElementDocument::SetStyleSheet(StyleSheet* _style_sheet)
  152. {
  153. if (style_sheet == _style_sheet)
  154. return;
  155. if (style_sheet != NULL)
  156. style_sheet->RemoveReference();
  157. style_sheet = _style_sheet;
  158. if (style_sheet != NULL)
  159. {
  160. style_sheet->AddReference();
  161. style_sheet->BuildNodeIndex();
  162. }
  163. GetStyle()->DirtyDefinition();
  164. }
  165. // Returns the document's style sheet.
  166. StyleSheet* ElementDocument::GetStyleSheet() const
  167. {
  168. return style_sheet;
  169. }
  170. // Brings the document to the front of the document stack.
  171. void ElementDocument::PullToFront()
  172. {
  173. if (context != NULL)
  174. context->PullDocumentToFront(this);
  175. }
  176. // Sends the document to the back of the document stack.
  177. void ElementDocument::PushToBack()
  178. {
  179. if (context != NULL)
  180. context->PushDocumentToBack(this);
  181. }
  182. void ElementDocument::Show(int focus_flags)
  183. {
  184. // Store the modal attribute
  185. modal = (focus_flags & MODAL) > 0;
  186. // Set to visible and switch focus if necessary
  187. SetProperty(VISIBILITY, Property(Style::Visibility::Visible));
  188. // We should update the document now, otherwise the focusing methods below do not think we are visible
  189. // If this turns out to be slow, the more performant approach is just to compute the new visibility property
  190. UpdateDocument();
  191. if (focus_flags & FOCUS || focus_flags & MODAL)
  192. {
  193. // If no element could be focused, focus the window
  194. if (!FocusNextTabElement(this, true))
  195. {
  196. Focus();
  197. }
  198. }
  199. DispatchEvent(EventId::Show, Dictionary());
  200. }
  201. void ElementDocument::Hide()
  202. {
  203. SetProperty(VISIBILITY, Property(Style::Visibility::Hidden));
  204. // We should update the document now, so that the focusing below will get the correct visibility
  205. UpdateDocument();
  206. DispatchEvent(EventId::Hide, Dictionary());
  207. if (context)
  208. {
  209. auto focus = context->GetFocusElement();
  210. if (focus && focus != this && focus->GetOwnerDocument() == this)
  211. Focus();
  212. }
  213. }
  214. // Close this document
  215. void ElementDocument::Close()
  216. {
  217. if (context != NULL)
  218. context->UnloadDocument(this);
  219. }
  220. Element* ElementDocument::CreateElement(const String& name)
  221. {
  222. return Factory::InstanceElement(NULL, name, name, XMLAttributes());
  223. }
  224. // Create a text element.
  225. ElementText* ElementDocument::CreateTextNode(const String& text)
  226. {
  227. // Create the element.
  228. Element* element = CreateElement("#text");
  229. if (!element)
  230. {
  231. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer returned NULL.");
  232. return NULL;
  233. }
  234. // Cast up
  235. ElementText* element_text = dynamic_cast< ElementText* >(element);
  236. if (!element_text)
  237. {
  238. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer didn't return a derivative of ElementText.");
  239. element->RemoveReference();
  240. return NULL;
  241. }
  242. // Set the text
  243. element_text->SetText(ToWideString(text));
  244. return element_text;
  245. }
  246. // Is the current document modal
  247. bool ElementDocument::IsModal() const
  248. {
  249. return modal && IsVisible();
  250. }
  251. // Default load script implementation
  252. void ElementDocument::LoadScript(Stream* ROCKET_UNUSED_PARAMETER(stream), const String& ROCKET_UNUSED_PARAMETER(source_name))
  253. {
  254. ROCKET_UNUSED(stream);
  255. ROCKET_UNUSED(source_name);
  256. }
  257. // Updates the document, including its layout
  258. void ElementDocument::UpdateDocument()
  259. {
  260. const float dp_ratio = (context ? context->GetDensityIndependentPixelRatio() : 1.0f);
  261. Update(dp_ratio);
  262. UpdateLayout();
  263. UpdatePosition();
  264. }
  265. // Updates the layout if necessary.
  266. void ElementDocument::UpdateLayout()
  267. {
  268. // Note: Carefully consider when to call this function for performance reasons.
  269. // Ideally, only called once per update loop.
  270. if(layout_dirty)
  271. {
  272. layout_dirty = false;
  273. Vector2f containing_block(0, 0);
  274. if (GetParentNode() != NULL)
  275. containing_block = GetParentNode()->GetBox().GetSize();
  276. LayoutEngine layout_engine;
  277. layout_engine.FormatElement(this, containing_block);
  278. }
  279. }
  280. // Updates the position of the document based on the style properties.
  281. void ElementDocument::UpdatePosition()
  282. {
  283. if(position_dirty)
  284. {
  285. position_dirty = false;
  286. // We are only positioned relative to our parent, so if we're not parented we may as well bail now.
  287. if (GetParentNode() == NULL)
  288. return;
  289. Vector2f position;
  290. // Work out our containing block; relative offsets are calculated against it.
  291. Vector2f containing_block = GetParentNode()->GetBox().GetSize(Box::CONTENT);
  292. auto& computed = GetComputedValues();
  293. if (computed.left.type != Style::Left::Auto)
  294. position.x = ResolveValue(computed.left, containing_block.x);
  295. else if (computed.right.type != Style::Right::Auto)
  296. position.x = (containing_block.x - GetBox().GetSize(Box::MARGIN).x) - ResolveValue(computed.right, containing_block.x);
  297. else
  298. position.x = GetBox().GetEdge(Box::MARGIN, Box::LEFT);
  299. if (computed.top.type != Style::Top::Auto)
  300. position.y = ResolveValue(computed.top, containing_block.y);
  301. else if (computed.bottom.type != Style::Bottom::Auto)
  302. position.y = (containing_block.y - GetBox().GetSize(Box::MARGIN).y) - ResolveValue(computed.bottom, containing_block.y);
  303. else
  304. position.y = GetBox().GetEdge(Box::MARGIN, Box::TOP);
  305. SetOffset(position, NULL);
  306. }
  307. }
  308. void ElementDocument::DirtyPosition()
  309. {
  310. position_dirty = true;
  311. }
  312. void ElementDocument::DirtyLayout()
  313. {
  314. layout_dirty = true;
  315. }
  316. bool ElementDocument::IsLayoutDirty()
  317. {
  318. return layout_dirty;
  319. }
  320. void ElementDocument::DirtyDpProperties()
  321. {
  322. GetStyle()->DirtyDpProperties();
  323. }
  324. // Repositions the document if necessary.
  325. void ElementDocument::OnPropertyChange(const PropertyNameList& changed_properties)
  326. {
  327. Element::OnPropertyChange(changed_properties);
  328. // If the document's font-size has been changed, we need to dirty all rem properties.
  329. if (changed_properties.find(FONT_SIZE) != changed_properties.end())
  330. GetStyle()->DirtyRemProperties();
  331. if (changed_properties.find(TOP) != changed_properties.end() ||
  332. changed_properties.find(RIGHT) != changed_properties.end() ||
  333. changed_properties.find(BOTTOM) != changed_properties.end() ||
  334. changed_properties.find(LEFT) != changed_properties.end())
  335. DirtyPosition();
  336. }
  337. // Processes the 'onpropertychange' event, checking for a change in position or size.
  338. void ElementDocument::ProcessDefaultAction(Event& event)
  339. {
  340. Element::ProcessDefaultAction(event);
  341. // Process generic keyboard events for this window in bubble phase
  342. if (event.GetPhase() == EventPhase::Bubble && event == KEYDOWN)
  343. {
  344. int key_identifier = event.GetParameter<int>("key_identifier", Input::KI_UNKNOWN);
  345. // Process TAB
  346. if (key_identifier == Input::KI_TAB)
  347. {
  348. FocusNextTabElement(event.GetTargetElement(), !event.GetParameter<bool>("shift_key", false));
  349. }
  350. // Process ENTER being pressed on a focusable object (emulate click)
  351. else if (key_identifier == Input::KI_RETURN ||
  352. key_identifier == Input::KI_NUMPADENTER)
  353. {
  354. Element* focus_node = GetFocusLeafNode();
  355. if (focus_node && focus_node->GetComputedValues().tab_index == Style::TabIndex::Auto)
  356. {
  357. focus_node->Click();
  358. }
  359. }
  360. }
  361. }
  362. void ElementDocument::OnResize()
  363. {
  364. DirtyPosition();
  365. }
  366. // Find the next element to focus, starting at the current element
  367. //
  368. // This algorithm is quite sneaky, I originally thought a depth first search would
  369. // work, but it appears not. What is required is to cut the tree in half along the nodes
  370. // from current_element up the root and then either traverse the tree in a clockwise or
  371. // anticlock wise direction depending if you're searching forward or backward respectively
  372. bool ElementDocument::FocusNextTabElement(Element* current_element, bool forward)
  373. {
  374. // If we're searching forward, check the immediate children of this node first off
  375. if (forward)
  376. {
  377. for (int i = 0; i < current_element->GetNumChildren(); i++)
  378. if (SearchFocusSubtree(current_element->GetChild(i), forward))
  379. return true;
  380. }
  381. // Now walk up the tree, testing either the bottom or top
  382. // of the tree, depending on whether we're going forwards
  383. // or backwards respectively
  384. //
  385. // If we make it all the way up to the document, then
  386. // we search the entire tree (to loop back round)
  387. bool search_enabled = false;
  388. Element* document = current_element->GetOwnerDocument();
  389. Element* child = current_element;
  390. Element* parent = current_element->GetParentNode();
  391. while (child != document)
  392. {
  393. for (int i = 0; i < parent->GetNumChildren(); i++)
  394. {
  395. // Calculate index into children
  396. int child_index = i;
  397. if (!forward)
  398. child_index = parent->GetNumChildren() - i - 1;
  399. Element* search_child = parent->GetChild(child_index);
  400. // Do a search if its enabled
  401. if (search_enabled && SearchFocusSubtree(search_child, forward))
  402. return true;
  403. // If we find the child, enable searching
  404. if (search_child == child)
  405. search_enabled = true;
  406. }
  407. // Advance up the tree
  408. child = parent;
  409. parent = parent->GetParentNode();
  410. // If we hit the top, enable searching the entire tree
  411. if (parent == document)
  412. search_enabled = true;
  413. else // otherwise enable searching if we're going backward and disable if we're going forward
  414. search_enabled = false;
  415. }
  416. return false;
  417. }
  418. bool ElementDocument::SearchFocusSubtree(Element* element, bool forward)
  419. {
  420. // Skip disabled elements
  421. if (element->IsPseudoClassSet("disabled"))
  422. {
  423. return false;
  424. }
  425. if (!element->IsVisible())
  426. {
  427. return false;
  428. }
  429. // Check if this is the node we're looking for
  430. if (element->GetComputedValues().tab_index == Style::TabIndex::Auto)
  431. {
  432. element->Focus();
  433. element->ScrollIntoView(false);
  434. return true;
  435. }
  436. // Check all children
  437. for (int i = 0; i < element->GetNumChildren(); i++)
  438. {
  439. int child_index = i;
  440. if (!forward)
  441. child_index = element->GetNumChildren() - i - 1;
  442. if (SearchFocusSubtree(element->GetChild(child_index), forward))
  443. return true;
  444. }
  445. return false;
  446. }
  447. }
  448. }