ElementDocument.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. // Combine any inline sheets.
  84. for (const DocumentHeader::Resource& rcss : header.rcss)
  85. {
  86. if (rcss.is_inline)
  87. {
  88. UniquePtr<StyleSheet> inline_sheet = MakeUnique<StyleSheet>();
  89. auto stream = MakeUnique<StreamMemory>((const byte*)rcss.content.c_str(), rcss.content.size());
  90. stream->SetSourceURL(rcss.path);
  91. if (inline_sheet->LoadStyleSheet(stream.get(), rcss.line))
  92. {
  93. if (new_style_sheet)
  94. {
  95. SharedPtr<StyleSheet> combined_sheet = new_style_sheet->CombineStyleSheet(*inline_sheet);
  96. new_style_sheet = combined_sheet;
  97. }
  98. else
  99. new_style_sheet = std::move(inline_sheet);
  100. }
  101. stream.reset();
  102. }
  103. else
  104. {
  105. SharedPtr<StyleSheet> sub_sheet = StyleSheetFactory::GetStyleSheet(rcss.path);
  106. if (sub_sheet)
  107. {
  108. if (new_style_sheet)
  109. {
  110. SharedPtr<StyleSheet> combined_sheet = new_style_sheet->CombineStyleSheet(*sub_sheet);
  111. new_style_sheet = std::move(combined_sheet);
  112. }
  113. else
  114. new_style_sheet = sub_sheet;
  115. }
  116. else
  117. Log::Message(Log::LT_ERROR, "Failed to load style sheet %s.", rcss.path.c_str());
  118. }
  119. }
  120. // If a style sheet is available, set it on the document and release it.
  121. if (new_style_sheet)
  122. {
  123. SetStyleSheet(std::move(new_style_sheet));
  124. }
  125. // Load scripts.
  126. for (const DocumentHeader::Resource& script : header.scripts)
  127. {
  128. if (script.is_inline)
  129. {
  130. LoadInlineScript(script.content, script.path, script.line);
  131. }
  132. else
  133. {
  134. LoadExternalScript(script.path);
  135. }
  136. }
  137. // Hide this document.
  138. SetProperty(PropertyId::Visibility, Property(Style::Visibility::Hidden));
  139. const float dp_ratio = (context ? context->GetDensityIndependentPixelRatio() : 1.0f);
  140. const Vector2f vp_dimensions = (context ? Vector2f(context->GetDimensions()) : Vector2f(1.0f));
  141. // Update properties so that e.g. visibility status can be queried properly immediately.
  142. UpdateProperties(dp_ratio, vp_dimensions);
  143. }
  144. // Returns the document's context.
  145. Context* ElementDocument::GetContext()
  146. {
  147. return context;
  148. }
  149. // Sets the document's title.
  150. void ElementDocument::SetTitle(const String& _title)
  151. {
  152. title = _title;
  153. }
  154. const String& ElementDocument::GetTitle() const
  155. {
  156. return title;
  157. }
  158. const String& ElementDocument::GetSourceURL() const
  159. {
  160. return source_url;
  161. }
  162. // Sets the style sheet this document, and all of its children, uses.
  163. void ElementDocument::SetStyleSheet(SharedPtr<StyleSheet> _style_sheet)
  164. {
  165. RMLUI_ZoneScoped;
  166. if (style_sheet == _style_sheet)
  167. return;
  168. style_sheet = std::move(_style_sheet);
  169. if (style_sheet)
  170. {
  171. style_sheet->BuildNodeIndex();
  172. style_sheet->OptimizeNodeProperties();
  173. }
  174. GetStyle()->DirtyDefinition();
  175. }
  176. // Returns the document's style sheet.
  177. const SharedPtr<StyleSheet>& ElementDocument::GetStyleSheet() const
  178. {
  179. return style_sheet;
  180. }
  181. // Reload the document's style sheet from source files.
  182. void ElementDocument::ReloadStyleSheet()
  183. {
  184. if (!context)
  185. return;
  186. auto stream = MakeUnique<StreamFile>();
  187. if (!stream->Open(source_url))
  188. {
  189. Log::Message(Log::LT_WARNING, "Failed to open file to reload style sheet in document: %s", source_url.c_str());
  190. return;
  191. }
  192. Factory::ClearStyleSheetCache();
  193. Factory::ClearTemplateCache();
  194. ElementPtr temp_doc = Factory::InstanceDocumentStream(nullptr, stream.get(), context->GetDocumentsBaseTag());
  195. if (!temp_doc) {
  196. Log::Message(Log::LT_WARNING, "Failed to reload style sheet, could not instance document: %s", source_url.c_str());
  197. return;
  198. }
  199. SetStyleSheet(temp_doc->GetStyleSheet());
  200. }
  201. // Brings the document to the front of the document stack.
  202. void ElementDocument::PullToFront()
  203. {
  204. if (context != nullptr)
  205. context->PullDocumentToFront(this);
  206. }
  207. // Sends the document to the back of the document stack.
  208. void ElementDocument::PushToBack()
  209. {
  210. if (context != nullptr)
  211. context->PushDocumentToBack(this);
  212. }
  213. void ElementDocument::Show(ModalFlag modal_flag, FocusFlag focus_flag)
  214. {
  215. switch (modal_flag)
  216. {
  217. case ModalFlag::None: modal = false; break;
  218. case ModalFlag::Modal: modal = true; break;
  219. case ModalFlag::Keep: break;
  220. }
  221. bool focus = false;
  222. bool autofocus = false;
  223. bool focus_previous = false;
  224. switch (focus_flag)
  225. {
  226. case FocusFlag::None:
  227. break;
  228. case FocusFlag::Document:
  229. focus = true;
  230. break;
  231. case FocusFlag::Keep:
  232. focus = true;
  233. focus_previous = true;
  234. break;
  235. case FocusFlag::Auto:
  236. focus = true;
  237. autofocus = true;
  238. break;
  239. }
  240. // Set to visible and switch focus if necessary
  241. SetProperty(PropertyId::Visibility, Property(Style::Visibility::Visible));
  242. // We should update the document now, otherwise the focusing methods below do not think we are visible
  243. // If this turns out to be slow, the more performant approach is just to compute the new visibility property
  244. UpdateDocument();
  245. if (focus)
  246. {
  247. Element* focus_element = this;
  248. if (autofocus)
  249. {
  250. Element* first_element = nullptr;
  251. Element* element = FindNextTabElement(this, true);
  252. while (element && element != first_element)
  253. {
  254. if (!first_element)
  255. first_element = element;
  256. if (element->HasAttribute("autofocus"))
  257. {
  258. focus_element = element;
  259. break;
  260. }
  261. element = FindNextTabElement(element, true);
  262. }
  263. }
  264. else if (focus_previous)
  265. {
  266. focus_element = GetFocusLeafNode();
  267. }
  268. // Focus the window or element
  269. bool focused = focus_element->Focus();
  270. if (focused && focus_element != this)
  271. focus_element->ScrollIntoView(false);
  272. }
  273. DispatchEvent(EventId::Show, Dictionary());
  274. }
  275. void ElementDocument::Hide()
  276. {
  277. SetProperty(PropertyId::Visibility, Property(Style::Visibility::Hidden));
  278. // We should update the document now, so that the (un)focusing will get the correct visibility
  279. UpdateDocument();
  280. DispatchEvent(EventId::Hide, Dictionary());
  281. if (context)
  282. {
  283. context->UnfocusDocument(this);
  284. }
  285. }
  286. // Close this document
  287. void ElementDocument::Close()
  288. {
  289. if (context != nullptr)
  290. context->UnloadDocument(this);
  291. }
  292. ElementPtr ElementDocument::CreateElement(const String& name)
  293. {
  294. return Factory::InstanceElement(nullptr, name, name, XMLAttributes());
  295. }
  296. // Create a text element.
  297. ElementPtr ElementDocument::CreateTextNode(const String& text)
  298. {
  299. // Create the element.
  300. ElementPtr element = CreateElement("#text");
  301. if (!element)
  302. {
  303. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer returned nullptr.");
  304. return nullptr;
  305. }
  306. // Cast up
  307. ElementText* element_text = rmlui_dynamic_cast< ElementText* >(element.get());
  308. if (!element_text)
  309. {
  310. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer didn't return a derivative of ElementText.");
  311. return nullptr;
  312. }
  313. // Set the text
  314. element_text->SetText(text);
  315. return element;
  316. }
  317. // Is the current document modal
  318. bool ElementDocument::IsModal() const
  319. {
  320. return modal && IsVisible();
  321. }
  322. // Default load inline script implementation
  323. void ElementDocument::LoadInlineScript(const String& RMLUI_UNUSED_PARAMETER(content), const String& RMLUI_UNUSED_PARAMETER(source_path), int RMLUI_UNUSED_PARAMETER(line))
  324. {
  325. RMLUI_UNUSED(content);
  326. RMLUI_UNUSED(source_path);
  327. RMLUI_UNUSED(line);
  328. }
  329. // Default load external script implementation
  330. void ElementDocument::LoadExternalScript(const String& RMLUI_UNUSED_PARAMETER(source_path))
  331. {
  332. RMLUI_UNUSED(source_path);
  333. }
  334. // Updates the document, including its layout
  335. void ElementDocument::UpdateDocument()
  336. {
  337. const float dp_ratio = (context ? context->GetDensityIndependentPixelRatio() : 1.0f);
  338. const Vector2f vp_dimensions = (context ? Vector2f(context->GetDimensions()) : Vector2f(1.0f));
  339. Update(dp_ratio, vp_dimensions);
  340. UpdateLayout();
  341. UpdatePosition();
  342. }
  343. // Updates the layout if necessary.
  344. void ElementDocument::UpdateLayout()
  345. {
  346. // Note: Carefully consider when to call this function for performance reasons.
  347. // Ideally, only called once per update loop.
  348. if(layout_dirty)
  349. {
  350. RMLUI_ZoneScoped;
  351. RMLUI_ZoneText(source_url.c_str(), source_url.size());
  352. Vector2f containing_block(0, 0);
  353. if (GetParentNode() != nullptr)
  354. containing_block = GetParentNode()->GetBox().GetSize();
  355. LayoutEngine::FormatElement(this, containing_block);
  356. // Ignore dirtied layout during document formatting. Layouting must not require re-iteration.
  357. // In particular, scrollbars being enabled may set the dirty flag, but this case is already handled within the layout engine.
  358. layout_dirty = false;
  359. }
  360. }
  361. // Updates the position of the document based on the style properties.
  362. void ElementDocument::UpdatePosition()
  363. {
  364. if(position_dirty)
  365. {
  366. RMLUI_ZoneScoped;
  367. position_dirty = false;
  368. Element* root = GetParentNode();
  369. // 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.
  370. if (!root || !context || (root != context->GetRootElement()))
  371. return;
  372. Vector2f position;
  373. // Work out our containing block; relative offsets are calculated against it.
  374. Vector2f containing_block = root->GetBox().GetSize(Box::CONTENT);
  375. auto& computed = GetComputedValues();
  376. if (computed.left.type != Style::Left::Auto)
  377. position.x = ResolveValue(computed.left, containing_block.x);
  378. else if (computed.right.type != Style::Right::Auto)
  379. position.x = (containing_block.x - GetBox().GetSize(Box::MARGIN).x) - ResolveValue(computed.right, containing_block.x);
  380. else
  381. position.x = GetBox().GetEdge(Box::MARGIN, Box::LEFT);
  382. if (computed.top.type != Style::Top::Auto)
  383. position.y = ResolveValue(computed.top, containing_block.y);
  384. else if (computed.bottom.type != Style::Bottom::Auto)
  385. position.y = (containing_block.y - GetBox().GetSize(Box::MARGIN).y) - ResolveValue(computed.bottom, containing_block.y);
  386. else
  387. position.y = GetBox().GetEdge(Box::MARGIN, Box::TOP);
  388. SetOffset(position, nullptr);
  389. }
  390. }
  391. void ElementDocument::DirtyPosition()
  392. {
  393. position_dirty = true;
  394. }
  395. void ElementDocument::DirtyLayout()
  396. {
  397. layout_dirty = true;
  398. }
  399. bool ElementDocument::IsLayoutDirty()
  400. {
  401. return layout_dirty;
  402. }
  403. void ElementDocument::DirtyDpProperties()
  404. {
  405. GetStyle()->DirtyPropertiesWithUnitsRecursive(Property::DP);
  406. }
  407. void ElementDocument::DirtyVwAndVhProperties()
  408. {
  409. GetStyle()->DirtyPropertiesWithUnitsRecursive(Property::VW | Property::VH);
  410. }
  411. // Repositions the document if necessary.
  412. void ElementDocument::OnPropertyChange(const PropertyIdSet& changed_properties)
  413. {
  414. Element::OnPropertyChange(changed_properties);
  415. // If the document's font-size has been changed, we need to dirty all rem properties.
  416. if (changed_properties.Contains(PropertyId::FontSize))
  417. GetStyle()->DirtyPropertiesWithUnitsRecursive(Property::REM);
  418. if (changed_properties.Contains(PropertyId::Top) ||
  419. changed_properties.Contains(PropertyId::Right) ||
  420. changed_properties.Contains(PropertyId::Bottom) ||
  421. changed_properties.Contains(PropertyId::Left))
  422. DirtyPosition();
  423. }
  424. // Processes the 'onpropertychange' event, checking for a change in position or size.
  425. void ElementDocument::ProcessDefaultAction(Event& event)
  426. {
  427. Element::ProcessDefaultAction(event);
  428. // Process generic keyboard events for this window in bubble phase
  429. if (event == EventId::Keydown)
  430. {
  431. int key_identifier = event.GetParameter<int>("key_identifier", Input::KI_UNKNOWN);
  432. // Process TAB
  433. if (key_identifier == Input::KI_TAB)
  434. {
  435. if (Element* element = FindNextTabElement(event.GetTargetElement(), !event.GetParameter<bool>("shift_key", false)))
  436. {
  437. if(element->Focus())
  438. {
  439. element->ScrollIntoView(false);
  440. event.StopPropagation();
  441. }
  442. }
  443. }
  444. // Process ENTER being pressed on a focusable object (emulate click)
  445. else if (key_identifier == Input::KI_RETURN ||
  446. key_identifier == Input::KI_NUMPADENTER)
  447. {
  448. Element* focus_node = GetFocusLeafNode();
  449. if (focus_node && focus_node->GetComputedValues().tab_index == Style::TabIndex::Auto)
  450. {
  451. focus_node->Click();
  452. event.StopPropagation();
  453. }
  454. }
  455. }
  456. }
  457. void ElementDocument::OnResize()
  458. {
  459. DirtyPosition();
  460. }
  461. enum class CanFocus { Yes, No, NoAndNoChildren };
  462. static CanFocus CanFocusElement(Element* element)
  463. {
  464. if (!element->IsVisible())
  465. return CanFocus::NoAndNoChildren;
  466. const ComputedValues& computed = element->GetComputedValues();
  467. if (computed.focus == Style::Focus::None)
  468. return CanFocus::NoAndNoChildren;
  469. if (computed.tab_index == Style::TabIndex::Auto)
  470. return CanFocus::Yes;
  471. return CanFocus::No;
  472. }
  473. // Find the next element to focus, starting at the current element
  474. //
  475. // This algorithm is quite sneaky, I originally thought a depth first search would
  476. // work, but it appears not. What is required is to cut the tree in half along the nodes
  477. // from current_element up the root and then either traverse the tree in a clockwise or
  478. // anticlock wise direction depending if you're searching forward or backward respectively
  479. Element* ElementDocument::FindNextTabElement(Element* current_element, bool forward)
  480. {
  481. // If we're searching forward, check the immediate children of this node first off.
  482. if (forward)
  483. {
  484. for (int i = 0; i < current_element->GetNumChildren(); i++)
  485. if (Element* result = SearchFocusSubtree(current_element->GetChild(i), forward))
  486. return result;
  487. }
  488. // Now walk up the tree, testing either the bottom or top
  489. // of the tree, depending on whether we're going forward
  490. // or backward respectively.
  491. bool search_enabled = false;
  492. Element* document = current_element->GetOwnerDocument();
  493. Element* child = current_element;
  494. Element* parent = current_element->GetParentNode();
  495. while (child != document)
  496. {
  497. const int num_children = parent->GetNumChildren();
  498. for (int i = 0; i < num_children; i++)
  499. {
  500. // Calculate index into children
  501. const int child_index = forward ? i : (num_children - i - 1);
  502. Element* search_child = parent->GetChild(child_index);
  503. // Do a search if its enabled
  504. if (search_enabled)
  505. if(Element* result = SearchFocusSubtree(search_child, forward))
  506. return result;
  507. // Enable searching when we reach the child.
  508. if (search_child == child)
  509. search_enabled = true;
  510. }
  511. // Advance up the tree
  512. child = parent;
  513. parent = parent->GetParentNode();
  514. search_enabled = false;
  515. }
  516. // We could not find anything to focus along this direction.
  517. // If we can focus the document, then focus that now.
  518. if (current_element != document && CanFocusElement(document) == CanFocus::Yes)
  519. return document;
  520. // Otherwise, search the entire document tree. This way we will wrap around.
  521. const int num_children = document->GetNumChildren();
  522. for (int i = 0; i < num_children; i++)
  523. {
  524. const int child_index = forward ? i : (num_children - i - 1);
  525. if (Element* result = SearchFocusSubtree(document->GetChild(child_index), forward))
  526. return result;
  527. }
  528. return nullptr;
  529. }
  530. Element* ElementDocument::SearchFocusSubtree(Element* element, bool forward)
  531. {
  532. CanFocus can_focus = CanFocusElement(element);
  533. if (can_focus == CanFocus::Yes)
  534. return element;
  535. else if (can_focus == CanFocus::NoAndNoChildren)
  536. return nullptr;
  537. // Check all children
  538. for (int i = 0; i < element->GetNumChildren(); i++)
  539. {
  540. int child_index = i;
  541. if (!forward)
  542. child_index = element->GetNumChildren() - i - 1;
  543. if (Element * result = SearchFocusSubtree(element->GetChild(child_index), forward))
  544. return result;
  545. }
  546. return nullptr;
  547. }
  548. } // namespace Rml