ElementDocument.cpp 16 KB

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