ElementDocument.cpp 19 KB

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