ElementDocument.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. lock_layout = 0;
  50. ForceLocalStackingContext();
  51. SetProperty(POSITION, "absolute");
  52. }
  53. ElementDocument::~ElementDocument()
  54. {
  55. if (style_sheet != NULL)
  56. style_sheet->RemoveReference();
  57. }
  58. void ElementDocument::ProcessHeader(const DocumentHeader* document_header)
  59. {
  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].CString());
  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. StyleSheet* style_sheet = NULL;
  81. if (header.rcss_external.size() > 0)
  82. 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. StyleSheet* new_sheet = new StyleSheet();
  89. StreamMemory* stream = new StreamMemory((const byte*) header.rcss_inline[i].CString(), header.rcss_inline[i].Length());
  90. stream->SetSourceURL(document_header->source);
  91. if (new_sheet->LoadStyleSheet(stream))
  92. {
  93. if (style_sheet)
  94. {
  95. StyleSheet* combined_sheet = style_sheet->CombineStyleSheet(new_sheet);
  96. style_sheet->RemoveReference();
  97. new_sheet->RemoveReference();
  98. style_sheet = combined_sheet;
  99. }
  100. else
  101. style_sheet = new_sheet;
  102. }
  103. else
  104. new_sheet->RemoveReference();
  105. stream->RemoveReference();
  106. }
  107. }
  108. // If a style sheet is available, set it on the document and release it.
  109. if (style_sheet)
  110. {
  111. SetStyleSheet(style_sheet);
  112. style_sheet->RemoveReference();
  113. }
  114. // Load external scripts.
  115. for (size_t i = 0; i < header.scripts_external.size(); i++)
  116. {
  117. StreamFile* stream = new StreamFile();
  118. if (stream->Open(header.scripts_external[i]))
  119. LoadScript(stream, header.scripts_external[i]);
  120. stream->RemoveReference();
  121. }
  122. // Load internal scripts.
  123. for (size_t i = 0; i < header.scripts_inline.size(); i++)
  124. {
  125. StreamMemory* stream = new StreamMemory((const byte*) header.scripts_inline[i].CString(), header.scripts_inline[i].Length());
  126. LoadScript(stream, "");
  127. stream->RemoveReference();
  128. }
  129. // Hide this document.
  130. SetProperty(VISIBILITY, "hidden");
  131. }
  132. ElementDocument* ElementDocument::GetOwnerDocument()
  133. {
  134. return this;
  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. // Sets the style sheet this document, and all of its children, uses.
  155. void ElementDocument::SetStyleSheet(StyleSheet* _style_sheet)
  156. {
  157. if (style_sheet == _style_sheet)
  158. return;
  159. if (style_sheet != NULL)
  160. style_sheet->RemoveReference();
  161. style_sheet = _style_sheet;
  162. if (style_sheet != NULL)
  163. {
  164. style_sheet->AddReference();
  165. style_sheet->BuildNodeIndex();
  166. }
  167. GetStyle()->DirtyDefinition();
  168. }
  169. // Returns the document's style sheet.
  170. StyleSheet* ElementDocument::GetStyleSheet() const
  171. {
  172. return style_sheet;
  173. }
  174. // Brings the document to the front of the document stack.
  175. void ElementDocument::PullToFront()
  176. {
  177. if (context != NULL)
  178. context->PullDocumentToFront(this);
  179. }
  180. // Sends the document to the back of the document stack.
  181. void ElementDocument::PushToBack()
  182. {
  183. if (context != NULL)
  184. context->PushDocumentToBack(this);
  185. }
  186. void ElementDocument::Show(int focus_flags)
  187. {
  188. // Store the modal attribute
  189. modal = (focus_flags & MODAL) > 0;
  190. // Set to visible and switch focus if necessary
  191. SetProperty(VISIBILITY, "visible");
  192. if (focus_flags & FOCUS || focus_flags & MODAL)
  193. {
  194. // If no element could be focused, focus the window
  195. if (!FocusNextTabElement(this, true))
  196. {
  197. Focus();
  198. }
  199. }
  200. DispatchEvent("show", Dictionary(), false);
  201. }
  202. void ElementDocument::Hide()
  203. {
  204. SetProperty(VISIBILITY, "hidden");
  205. DispatchEvent("hide", Dictionary(), false);
  206. if (context)
  207. {
  208. auto focus = context->GetFocusElement();
  209. if (focus && focus != this && focus->GetOwnerDocument() == this)
  210. Focus();
  211. }
  212. }
  213. // Close this document
  214. void ElementDocument::Close()
  215. {
  216. if (context != NULL)
  217. context->UnloadDocument(this);
  218. }
  219. Element* ElementDocument::CreateElement(const String& name)
  220. {
  221. return Factory::InstanceElement(NULL, name, name, XMLAttributes());
  222. }
  223. // Create a text element.
  224. ElementText* ElementDocument::CreateTextNode(const String& text)
  225. {
  226. // Create the element.
  227. Element* element = CreateElement("#text");
  228. if (!element)
  229. {
  230. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer returned NULL.");
  231. return NULL;
  232. }
  233. // Cast up
  234. ElementText* element_text = dynamic_cast< ElementText* >(element);
  235. if (!element_text)
  236. {
  237. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer didn't return a derivative of ElementText.");
  238. element->RemoveReference();
  239. return NULL;
  240. }
  241. // Set the text
  242. element_text->SetText(text);
  243. return element_text;
  244. }
  245. // Is the current document modal
  246. bool ElementDocument::IsModal() const
  247. {
  248. return modal && IsVisible();
  249. }
  250. // Default load script implementation
  251. void ElementDocument::LoadScript(Stream* RMLUI_UNUSED_PARAMETER(stream), const String& RMLUI_UNUSED_PARAMETER(source_name))
  252. {
  253. RMLUI_UNUSED(stream);
  254. RMLUI_UNUSED(source_name);
  255. }
  256. // Updates the layout if necessary.
  257. void ElementDocument::_UpdateLayout()
  258. {
  259. const int max_updates = 3;
  260. lock_layout++;
  261. for(int i = 0; layout_dirty && i < max_updates; i++)
  262. {
  263. layout_dirty = false;
  264. Vector2f containing_block(0, 0);
  265. if (GetParentNode() != NULL)
  266. containing_block = GetParentNode()->GetBox().GetSize();
  267. LayoutEngine layout_engine;
  268. layout_engine.FormatElement(this, containing_block);
  269. }
  270. lock_layout--;
  271. }
  272. // Updates the position of the document based on the style properties.
  273. void ElementDocument::UpdatePosition()
  274. {
  275. // We are only positioned relative to our parent, so if we're not parented we may as well bail now.
  276. if (GetParentNode() == NULL)
  277. return;
  278. Vector2f position;
  279. // Work out our containing block; relative offsets are calculated against it.
  280. Vector2f containing_block = GetParentNode()->GetBox().GetSize(Box::CONTENT);
  281. const Property *left = GetLocalProperty(LEFT);
  282. const Property *right = GetLocalProperty(RIGHT);
  283. if (left != NULL && left->unit != Property::KEYWORD)
  284. position.x = ResolveProperty(LEFT, containing_block.x);
  285. else if (right != NULL && right->unit != Property::KEYWORD)
  286. position.x = (containing_block.x - GetBox().GetSize(Box::MARGIN).x) - ResolveProperty(RIGHT, containing_block.x);
  287. else
  288. position.x = GetBox().GetEdge(Box::MARGIN, Box::LEFT);
  289. const Property *top = GetLocalProperty(TOP);
  290. const Property *bottom = GetLocalProperty(BOTTOM);
  291. if (top != NULL && top->unit != Property::KEYWORD)
  292. position.y = ResolveProperty(TOP, containing_block.y);
  293. else if (bottom != NULL && bottom->unit != Property::KEYWORD)
  294. position.y = (containing_block.y - GetBox().GetSize(Box::MARGIN).y) - ResolveProperty(BOTTOM, containing_block.y);
  295. else
  296. position.y = GetBox().GetEdge(Box::MARGIN, Box::TOP);
  297. SetOffset(position, NULL);
  298. }
  299. void ElementDocument::LockLayout(bool lock)
  300. {
  301. if (lock)
  302. lock_layout++;
  303. else
  304. lock_layout--;
  305. RMLUI_ASSERT(lock_layout >= 0);
  306. }
  307. void ElementDocument::DirtyLayout()
  308. {
  309. layout_dirty = true;
  310. }
  311. bool ElementDocument::IsLayoutDirty()
  312. {
  313. return layout_dirty;
  314. }
  315. void ElementDocument::DirtyDpProperties()
  316. {
  317. GetStyle()->DirtyDpProperties();
  318. }
  319. // Refreshes the document layout if required.
  320. void ElementDocument::OnUpdate()
  321. {
  322. UpdateLayout();
  323. }
  324. // Repositions the document if necessary.
  325. void ElementDocument::OnPropertyChange(const PropertyNameList& changed_properties)
  326. {
  327. Element::OnPropertyChange(changed_properties);
  328. // If the document's font-size has been changed, we need to dirty all rem properties.
  329. if (changed_properties.find(FONT_SIZE) != changed_properties.end())
  330. GetStyle()->DirtyRemProperties();
  331. if (changed_properties.find(TOP) != changed_properties.end() ||
  332. changed_properties.find(RIGHT) != changed_properties.end() ||
  333. changed_properties.find(BOTTOM) != changed_properties.end() ||
  334. changed_properties.find(LEFT) != changed_properties.end())
  335. UpdatePosition();
  336. }
  337. // Processes the 'onpropertychange' event, checking for a change in position or size.
  338. void ElementDocument::ProcessEvent(Event& event)
  339. {
  340. Element::ProcessEvent(event);
  341. // Process generic keyboard events for this window in capture phase
  342. if (event.GetPhase() == Event::PHASE_BUBBLE && event == KEYDOWN)
  343. {
  344. int key_identifier = event.GetParameter<int>("key_identifier", Input::KI_UNKNOWN);
  345. // Process TAB
  346. if (key_identifier == Input::KI_TAB)
  347. {
  348. FocusNextTabElement(event.GetTargetElement(), !event.GetParameter<bool>("shift_key", false));
  349. }
  350. // Process ENTER being pressed on a focusable object (emulate click)
  351. else if (key_identifier == Input::KI_RETURN ||
  352. key_identifier == Input::KI_NUMPADENTER)
  353. {
  354. Element* focus_node = GetFocusLeafNode();
  355. if (focus_node && focus_node->GetProperty<int>(TAB_INDEX) == TAB_INDEX_AUTO)
  356. {
  357. focus_node->Click();
  358. }
  359. }
  360. }
  361. else if (event.GetTargetElement() == this)
  362. {
  363. if (event == RESIZE)
  364. UpdatePosition();
  365. }
  366. }
  367. // Find the next element to focus, starting at the current element
  368. //
  369. // This algorithm is quite sneaky, I originally thought a depth first search would
  370. // work, but it appears not. What is required is to cut the tree in half along the nodes
  371. // from current_element up the root and then either traverse the tree in a clockwise or
  372. // anticlock wise direction depending if you're searching forward or backward respectively
  373. bool ElementDocument::FocusNextTabElement(Element* current_element, bool forward)
  374. {
  375. // If we're searching forward, check the immediate children of this node first off
  376. if (forward)
  377. {
  378. for (int i = 0; i < current_element->GetNumChildren(); i++)
  379. if (SearchFocusSubtree(current_element->GetChild(i), forward))
  380. return true;
  381. }
  382. // Now walk up the tree, testing either the bottom or top
  383. // of the tree, depending on whether we're going forwards
  384. // or backwards respectively
  385. //
  386. // If we make it all the way up to the document, then
  387. // we search the entire tree (to loop back round)
  388. bool search_enabled = false;
  389. Element* document = current_element->GetOwnerDocument();
  390. Element* child = current_element;
  391. Element* parent = current_element->GetParentNode();
  392. while (child != document)
  393. {
  394. for (int i = 0; i < parent->GetNumChildren(); i++)
  395. {
  396. // Calculate index into children
  397. int child_index = i;
  398. if (!forward)
  399. child_index = parent->GetNumChildren() - i - 1;
  400. Element* search_child = parent->GetChild(child_index);
  401. // Do a search if its enabled
  402. if (search_enabled && SearchFocusSubtree(search_child, forward))
  403. return true;
  404. // If we find the child, enable searching
  405. if (search_child == child)
  406. search_enabled = true;
  407. }
  408. // Advance up the tree
  409. child = parent;
  410. parent = parent->GetParentNode();
  411. // If we hit the top, enable searching the entire tree
  412. if (parent == document)
  413. search_enabled = true;
  414. else // otherwise enable searching if we're going backward and disable if we're going forward
  415. search_enabled = false;
  416. }
  417. return false;
  418. }
  419. bool ElementDocument::SearchFocusSubtree(Element* element, bool forward)
  420. {
  421. // Skip disabled elements
  422. if (element->IsPseudoClassSet("disabled"))
  423. {
  424. return false;
  425. }
  426. if (!element->IsVisible())
  427. {
  428. return false;
  429. }
  430. // Check if this is the node we're looking for
  431. if (element->GetProperty<int>(TAB_INDEX) == TAB_INDEX_AUTO)
  432. {
  433. element->Focus();
  434. element->ScrollIntoView(false);
  435. return true;
  436. }
  437. // Check all children
  438. for (int i = 0; i < element->GetNumChildren(); i++)
  439. {
  440. int child_index = i;
  441. if (!forward)
  442. child_index = element->GetNumChildren() - i - 1;
  443. if (SearchFocusSubtree(element->GetChild(child_index), forward))
  444. return true;
  445. }
  446. return false;
  447. }
  448. }
  449. }