ElementDocument.cpp 16 KB

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