ElementDocument.cpp 18 KB

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