ElementDocument.cpp 15 KB

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