ElementDocument.cpp 15 KB

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