ElementDocument.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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/ElementUtilities.h"
  32. #include "../../Include/RmlUi/Core/Factory.h"
  33. #include "../../Include/RmlUi/Core/Profiling.h"
  34. #include "../../Include/RmlUi/Core/StreamMemory.h"
  35. #include "../../Include/RmlUi/Core/StyleSheet.h"
  36. #include "../../Include/RmlUi/Core/StyleSheetContainer.h"
  37. #include "DocumentHeader.h"
  38. #include "ElementStyle.h"
  39. #include "EventDispatcher.h"
  40. #include "Layout/LayoutDetails.h"
  41. #include "Layout/LayoutEngine.h"
  42. #include "Layout/LayoutNode.h"
  43. #include "StreamFile.h"
  44. #include "StyleSheetFactory.h"
  45. #include "Template.h"
  46. #include "TemplateCache.h"
  47. #include "XMLParseTools.h"
  48. #include <limits.h>
  49. namespace Rml {
  50. enum class NavigationSearchDirection { Up, Down, Left, Right };
  51. namespace {
  52. constexpr int Infinite = INT_MAX;
  53. struct BoundingBox {
  54. static const BoundingBox Invalid;
  55. Vector2f min;
  56. Vector2f max;
  57. BoundingBox(const Vector2f& min, const Vector2f& max) : min(min), max(max) {}
  58. BoundingBox Union(const BoundingBox& bounding_box) const
  59. {
  60. return BoundingBox(Math::Min(min, bounding_box.min), Math::Max(max, bounding_box.max));
  61. }
  62. bool Intersects(const BoundingBox& box) const { return min.x <= box.max.x && max.x >= box.min.x && min.y <= box.max.y && max.y >= box.min.y; }
  63. bool IsValid() const { return min.x <= max.x && min.y <= max.y; }
  64. };
  65. const BoundingBox BoundingBox::Invalid = {Vector2f(FLT_MAX, FLT_MAX), Vector2f(-FLT_MAX, -FLT_MAX)};
  66. enum class CanFocus { Yes, No, NoAndNoChildren };
  67. CanFocus CanFocusElement(Element* element)
  68. {
  69. if (!element->IsVisible())
  70. return CanFocus::NoAndNoChildren;
  71. const ComputedValues& computed = element->GetComputedValues();
  72. if (computed.focus() == Style::Focus::None)
  73. return CanFocus::NoAndNoChildren;
  74. if (computed.tab_index() == Style::TabIndex::Auto)
  75. return CanFocus::Yes;
  76. return CanFocus::No;
  77. }
  78. bool IsScrollContainer(Element* element)
  79. {
  80. const auto& computed = element->GetComputedValues();
  81. return LayoutDetails::IsScrollContainer(computed.overflow_x(), computed.overflow_y());
  82. }
  83. int GetNavigationHeuristic(const BoundingBox& source, const BoundingBox& target, NavigationSearchDirection direction)
  84. {
  85. enum Axis { Horizontal = 0, Vertical = 1 };
  86. auto CalculateHeuristic = [](Axis axis, const BoundingBox& a, const BoundingBox& b) -> int {
  87. // The heuristic is mainly the distance from the source to the target along the specified direction. In
  88. // addition, the following factor determines the penalty for being outside the projected area of the element in
  89. // the given direction, as a multiplier of the cross-axis distance between the target and projected area.
  90. static constexpr int CrossAxisFactor = 10'000;
  91. const int main_axis = int(a.min[axis] - b.max[axis]);
  92. if (main_axis < 0)
  93. return Infinite;
  94. const Axis cross = Axis((axis + 1) % 2);
  95. const int cross_axis = Math::Max(0, int(b.min[cross] - a.max[cross])) + Math::Max(0, int(a.min[cross] - b.max[cross]));
  96. return main_axis + CrossAxisFactor * cross_axis;
  97. };
  98. switch (direction)
  99. {
  100. case NavigationSearchDirection::Up: return CalculateHeuristic(Vertical, source, target);
  101. case NavigationSearchDirection::Down: return CalculateHeuristic(Vertical, target, source);
  102. case NavigationSearchDirection::Right: return CalculateHeuristic(Horizontal, target, source);
  103. case NavigationSearchDirection::Left: return CalculateHeuristic(Horizontal, source, target);
  104. }
  105. RMLUI_ERROR;
  106. return Infinite;
  107. }
  108. struct SearchNavigationResult {
  109. Element* element = nullptr;
  110. int heuristic = Infinite;
  111. };
  112. // Search all descendents to determine which element minimizes the navigation heuristic.
  113. void SearchNavigationTarget(SearchNavigationResult& best_result, Element* element, NavigationSearchDirection direction,
  114. const BoundingBox& bounding_box, Element* exclude_element)
  115. {
  116. const int num_children = element->GetNumChildren();
  117. for (int child_index = 0; child_index < num_children; child_index++)
  118. {
  119. Element* child = element->GetChild(child_index);
  120. if (child == exclude_element)
  121. continue;
  122. const CanFocus can_focus = CanFocusElement(child);
  123. if (can_focus == CanFocus::Yes)
  124. {
  125. const Vector2f position = child->GetAbsoluteOffset(BoxArea::Border);
  126. const BoundingBox target_box = {position, position + child->GetBox().GetSize(BoxArea::Border)};
  127. const int heuristic = GetNavigationHeuristic(bounding_box, target_box, direction);
  128. if (heuristic < best_result.heuristic)
  129. {
  130. best_result.element = child;
  131. best_result.heuristic = heuristic;
  132. }
  133. }
  134. else if (can_focus == CanFocus::NoAndNoChildren || IsScrollContainer(child))
  135. {
  136. continue;
  137. }
  138. SearchNavigationTarget(best_result, child, direction, bounding_box, exclude_element);
  139. }
  140. }
  141. } // namespace
  142. ElementDocument::ElementDocument(const String& tag) : Element(tag)
  143. {
  144. context = nullptr;
  145. modal = false;
  146. focusable_from_modal = false;
  147. layout_dirty = true;
  148. position_dirty = false;
  149. ForceLocalStackingContext();
  150. SetOwnerDocument(this);
  151. SetProperty(PropertyId::Position, Property(Style::Position::Absolute));
  152. }
  153. ElementDocument::~ElementDocument() {}
  154. void ElementDocument::ProcessHeader(const DocumentHeader* document_header)
  155. {
  156. RMLUI_ZoneScoped;
  157. // Store the source address that we came from
  158. source_url = document_header->source;
  159. // Construct a new header and copy the template details across
  160. DocumentHeader header;
  161. header.MergePaths(header.template_resources, document_header->template_resources, document_header->source);
  162. // Merge in any templates, note a merge may cause more templates to merge
  163. for (size_t i = 0; i < header.template_resources.size(); i++)
  164. {
  165. Template* merge_template = TemplateCache::LoadTemplate(URL(header.template_resources[i]).GetURL());
  166. if (merge_template)
  167. header.MergeHeader(*merge_template->GetHeader());
  168. else
  169. Log::Message(Log::LT_WARNING, "Template %s not found", header.template_resources[i].c_str());
  170. }
  171. // Merge the document's header last, as it is the most overriding.
  172. header.MergeHeader(*document_header);
  173. // Set the title to the document title.
  174. title = document_header->title;
  175. // If a style-sheet (or sheets) has been specified for this element, then we load them and set the combined sheet
  176. // on the element; all of its children will inherit it by default.
  177. SharedPtr<StyleSheetContainer> new_style_sheet;
  178. // Combine any inline sheets.
  179. for (const DocumentHeader::Resource& rcss : header.rcss)
  180. {
  181. if (rcss.is_inline)
  182. {
  183. auto inline_sheet = MakeShared<StyleSheetContainer>();
  184. auto stream = MakeUnique<StreamMemory>((const byte*)rcss.content.c_str(), rcss.content.size());
  185. stream->SetSourceURL(rcss.path);
  186. if (inline_sheet->LoadStyleSheetContainer(stream.get(), rcss.line))
  187. {
  188. if (new_style_sheet)
  189. new_style_sheet->MergeStyleSheetContainer(*inline_sheet);
  190. else
  191. new_style_sheet = std::move(inline_sheet);
  192. }
  193. stream.reset();
  194. }
  195. else
  196. {
  197. const StyleSheetContainer* sub_sheet = StyleSheetFactory::GetStyleSheetContainer(rcss.path);
  198. if (sub_sheet)
  199. {
  200. if (new_style_sheet)
  201. new_style_sheet->MergeStyleSheetContainer(*sub_sheet);
  202. else
  203. new_style_sheet = sub_sheet->CombineStyleSheetContainer(StyleSheetContainer());
  204. }
  205. else
  206. Log::Message(Log::LT_ERROR, "Failed to load style sheet %s.", rcss.path.c_str());
  207. }
  208. }
  209. // If a style sheet is available, set it on the document.
  210. if (new_style_sheet)
  211. SetStyleSheetContainer(std::move(new_style_sheet));
  212. // Load scripts.
  213. for (const DocumentHeader::Resource& script : header.scripts)
  214. {
  215. if (script.is_inline)
  216. {
  217. LoadInlineScript(script.content, script.path, script.line);
  218. }
  219. else
  220. {
  221. LoadExternalScript(script.path);
  222. }
  223. }
  224. // Hide this document.
  225. SetProperty(PropertyId::Visibility, Property(Style::Visibility::Hidden));
  226. const float dp_ratio = (context ? context->GetDensityIndependentPixelRatio() : 1.0f);
  227. const Vector2f vp_dimensions = (context ? Vector2f(context->GetDimensions()) : Vector2f(1.0f));
  228. // Update properties so that e.g. visibility status can be queried properly immediately.
  229. UpdateProperties(dp_ratio, vp_dimensions);
  230. }
  231. Context* ElementDocument::GetContext()
  232. {
  233. return context;
  234. }
  235. void ElementDocument::SetTitle(const String& _title)
  236. {
  237. title = _title;
  238. }
  239. const String& ElementDocument::GetTitle() const
  240. {
  241. return title;
  242. }
  243. const String& ElementDocument::GetSourceURL() const
  244. {
  245. return source_url;
  246. }
  247. const StyleSheet* ElementDocument::GetStyleSheet() const
  248. {
  249. if (style_sheet_container)
  250. return style_sheet_container->GetCompiledStyleSheet();
  251. return nullptr;
  252. }
  253. const StyleSheetContainer* ElementDocument::GetStyleSheetContainer() const
  254. {
  255. return style_sheet_container.get();
  256. }
  257. void ElementDocument::SetStyleSheetContainer(SharedPtr<StyleSheetContainer> _style_sheet_container)
  258. {
  259. RMLUI_ZoneScoped;
  260. if (style_sheet_container == _style_sheet_container)
  261. return;
  262. style_sheet_container = std::move(_style_sheet_container);
  263. DirtyMediaQueries();
  264. }
  265. void ElementDocument::ReloadStyleSheet()
  266. {
  267. if (!context)
  268. return;
  269. auto stream = MakeUnique<StreamFile>();
  270. if (!stream->Open(source_url))
  271. {
  272. Log::Message(Log::LT_WARNING, "Failed to open file to reload style sheet in document: %s", source_url.c_str());
  273. return;
  274. }
  275. Factory::ClearStyleSheetCache();
  276. Factory::ClearTemplateCache();
  277. ElementPtr temp_doc = Factory::InstanceDocumentStream(nullptr, stream.get(), context->GetDocumentsBaseTag());
  278. if (!temp_doc)
  279. {
  280. Log::Message(Log::LT_WARNING, "Failed to reload style sheet, could not instance document: %s", source_url.c_str());
  281. return;
  282. }
  283. SetStyleSheetContainer(rmlui_static_cast<ElementDocument*>(temp_doc.get())->style_sheet_container);
  284. }
  285. void ElementDocument::DirtyMediaQueries()
  286. {
  287. if (context && style_sheet_container)
  288. {
  289. const bool changed_style_sheet = style_sheet_container->UpdateCompiledStyleSheet(context);
  290. if (changed_style_sheet)
  291. {
  292. DirtyDefinition(Element::DirtyNodes::Self);
  293. OnStyleSheetChangeRecursive();
  294. }
  295. }
  296. }
  297. void ElementDocument::PullToFront()
  298. {
  299. if (context != nullptr)
  300. context->PullDocumentToFront(this);
  301. }
  302. void ElementDocument::PushToBack()
  303. {
  304. if (context != nullptr)
  305. context->PushDocumentToBack(this);
  306. }
  307. void ElementDocument::Show(ModalFlag modal_flag, FocusFlag focus_flag)
  308. {
  309. switch (modal_flag)
  310. {
  311. case ModalFlag::None: modal = false; break;
  312. case ModalFlag::Modal: modal = true; break;
  313. case ModalFlag::Keep: break;
  314. }
  315. bool focus = false;
  316. bool autofocus = false;
  317. bool focus_previous = false;
  318. switch (focus_flag)
  319. {
  320. case FocusFlag::None: break;
  321. case FocusFlag::Document: focus = true; break;
  322. case FocusFlag::Keep:
  323. focus = true;
  324. focus_previous = true;
  325. break;
  326. case FocusFlag::Auto:
  327. focus = true;
  328. autofocus = true;
  329. break;
  330. }
  331. // Set to visible and switch focus if necessary.
  332. SetProperty(PropertyId::Visibility, Property(Style::Visibility::Visible));
  333. // Update the document now, otherwise the focusing methods below do not think we are visible. This is also important
  334. // to ensure correct layout for any event handlers, such as for focused input fields to submit the proper caret
  335. // position.
  336. UpdateDocument();
  337. if (focus)
  338. {
  339. Element* focus_element = this;
  340. if (autofocus)
  341. {
  342. Element* first_element = nullptr;
  343. Element* element = FindNextTabElement(this, true);
  344. while (element && element != first_element)
  345. {
  346. if (!first_element)
  347. first_element = element;
  348. if (element->HasAttribute("autofocus"))
  349. {
  350. focus_element = element;
  351. break;
  352. }
  353. element = FindNextTabElement(element, true);
  354. }
  355. }
  356. else if (focus_previous)
  357. {
  358. focus_element = GetFocusLeafNode();
  359. }
  360. // Focus the window or element
  361. bool focused = focus_element->Focus(true);
  362. if (focused && focus_element != this)
  363. focus_element->ScrollIntoView(false);
  364. }
  365. DispatchEvent(EventId::Show, Dictionary());
  366. }
  367. void ElementDocument::Hide()
  368. {
  369. SetProperty(PropertyId::Visibility, Property(Style::Visibility::Hidden));
  370. // We should update the document now, so that the (un)focusing will get the correct visibility
  371. UpdateDocument();
  372. DispatchEvent(EventId::Hide, Dictionary());
  373. if (context)
  374. {
  375. context->UnfocusDocument(this);
  376. }
  377. }
  378. void ElementDocument::Close()
  379. {
  380. if (context != nullptr)
  381. context->UnloadDocument(this);
  382. }
  383. ElementPtr ElementDocument::CreateElement(const String& name)
  384. {
  385. return Factory::InstanceElement(nullptr, name, name, XMLAttributes());
  386. }
  387. ElementPtr ElementDocument::CreateTextNode(const String& text)
  388. {
  389. // Create the element.
  390. ElementPtr element = CreateElement("#text");
  391. if (!element)
  392. {
  393. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer returned nullptr.");
  394. return nullptr;
  395. }
  396. // Cast up
  397. ElementText* element_text = rmlui_dynamic_cast<ElementText*>(element.get());
  398. if (!element_text)
  399. {
  400. Log::Message(Log::LT_ERROR, "Failed to create text element, instancer didn't return a derivative of ElementText.");
  401. return nullptr;
  402. }
  403. // Set the text
  404. element_text->SetText(text);
  405. return element;
  406. }
  407. bool ElementDocument::IsModal() const
  408. {
  409. return modal && IsVisible();
  410. }
  411. void ElementDocument::LoadInlineScript(const String& /*content*/, const String& /*source_path*/, int /*line*/) {}
  412. void ElementDocument::LoadExternalScript(const String& /*source_path*/) {}
  413. void ElementDocument::UpdateDocument()
  414. {
  415. const float dp_ratio = (context ? context->GetDensityIndependentPixelRatio() : 1.0f);
  416. const Vector2f vp_dimensions = (context ? Vector2f(context->GetDimensions()) : Vector2f(1.0f));
  417. Update(dp_ratio, vp_dimensions, true);
  418. UpdateLayout();
  419. UpdatePosition();
  420. }
  421. void ElementDocument::UpdatePropertiesForDebug()
  422. {
  423. const float dp_ratio = (context ? context->GetDensityIndependentPixelRatio() : 1.0f);
  424. const Vector2f vp_dimensions = (context ? Vector2f(context->GetDimensions()) : Vector2f(1.0f));
  425. Update(dp_ratio, vp_dimensions, true);
  426. }
  427. void ElementDocument::UpdateLayout()
  428. {
  429. // Note: Carefully consider when to call this function for performance reasons.
  430. // Ideally, only called once per update loop.
  431. if (layout_dirty)
  432. {
  433. RMLUI_ZoneScoped;
  434. RMLUI_ZoneText(source_url.c_str(), source_url.size());
  435. const bool allow_layout_cache = !HasAttribute("rmlui-disable-layout-cache");
  436. constexpr bool debug_logging = false;
  437. if (debug_logging)
  438. Log::Message(Log::LT_INFO, "UpdateLayout start: %s", GetAddress().c_str());
  439. bool force_full_document_layout = !allow_layout_cache;
  440. bool any_layout_updates = false;
  441. if (!force_full_document_layout)
  442. {
  443. ElementUtilities::BreadthFirstSearch(this, [&](Element* element) {
  444. if (element->GetDisplay() == Style::Display::None)
  445. return ElementUtilities::CallbackControlFlow::SkipChildren;
  446. LayoutNode* layout_node = element->GetLayoutNode();
  447. if (!layout_node->IsDirty())
  448. return ElementUtilities::CallbackControlFlow::Continue;
  449. if (!layout_node->IsLayoutBoundary())
  450. {
  451. // Normally the dirty layout should have propagated to the closest layout boundary during
  452. // Element::Update(), which then invokes formatting on that boundary element, and which again clears the
  453. // dirty layout on this element. This didn't happen here, which may be caused by modifying the layout
  454. // during layouting itself. For now, we simply skip this element and keep going. The element should
  455. // normally be properly layed-out on the next context update.
  456. // TODO: Might want to investigate this further.
  457. if (debug_logging)
  458. Log::Message(Log::LT_INFO, "Dirty layout on non-layout boundary element: %s", element->GetAddress().c_str());
  459. return ElementUtilities::CallbackControlFlow::Continue;
  460. }
  461. any_layout_updates = true;
  462. const Optional<CommittedLayout>& committed_layout = layout_node->GetCommittedLayout();
  463. if (!committed_layout)
  464. {
  465. if (element != this && debug_logging)
  466. Log::Message(Log::LT_INFO, "Forcing full layout update due to missing committed layout on element: %s",
  467. element->GetAddress().c_str());
  468. force_full_document_layout = true;
  469. // TODO: When is the committed layout dirtied?
  470. return ElementUtilities::CallbackControlFlow::Break;
  471. }
  472. if (element != this && debug_logging)
  473. Log::Message(Log::LT_INFO, "Doing partial layout update on element: %s", element->GetAddress().c_str());
  474. // TODO: In some cases, we need to check if size changed, such that we need to do a layout update in its parent.
  475. LayoutEngine::FormatElement(element, committed_layout->containing_block_size,
  476. committed_layout->absolutely_positioning_containing_block_size, allow_layout_cache);
  477. // TODO: A bit ugly
  478. element->UpdateRelativeOffsetFromInsetConstraints();
  479. return ElementUtilities::CallbackControlFlow::SkipChildren;
  480. });
  481. }
  482. if (force_full_document_layout)
  483. {
  484. Vector2f containing_block;
  485. if (Element* parent = GetParentNode())
  486. containing_block = parent->GetBox().GetSize();
  487. LayoutEngine::FormatElement(this, containing_block, containing_block, allow_layout_cache);
  488. // TODO: A bit ugly
  489. this->UpdateRelativeOffsetFromInsetConstraints();
  490. }
  491. if (!any_layout_updates && debug_logging)
  492. Log::Message(Log::LT_INFO, "Didn't make any layout updates on dirty document: %s", GetAddress().c_str());
  493. // Ignore dirtied layout during document formatting. Layouting must not require re-iteration.
  494. // In particular, scrollbars being enabled may set the dirty flag, but this case is already handled within the layout engine.
  495. layout_dirty = false;
  496. if (debug_logging)
  497. Log::Message(Log::LT_INFO, "Document layout: Clear dirty on %s", GetAddress().c_str());
  498. }
  499. }
  500. void ElementDocument::UpdatePosition()
  501. {
  502. if (position_dirty)
  503. {
  504. RMLUI_ZoneScoped;
  505. position_dirty = false;
  506. Element* root = GetParentNode();
  507. // We only position ourselves if we are a child of our context's root element. That is, we don't want to proceed
  508. // if we are unparented or an iframe document.
  509. if (!root || !context || (root != context->GetRootElement()))
  510. return;
  511. // Work out our containing block; relative offsets are calculated against it.
  512. const Vector2f containing_block = root->GetBox().GetSize();
  513. auto& computed = GetComputedValues();
  514. const Box& box = GetBox();
  515. Vector2f position;
  516. if (computed.left().type != Style::Left::Auto)
  517. position.x = ResolveValue(computed.left(), containing_block.x);
  518. else if (computed.right().type != Style::Right::Auto)
  519. position.x = containing_block.x - (box.GetSize(BoxArea::Margin).x + ResolveValue(computed.right(), containing_block.x));
  520. if (computed.top().type != Style::Top::Auto)
  521. position.y = ResolveValue(computed.top(), containing_block.y);
  522. else if (computed.bottom().type != Style::Bottom::Auto)
  523. position.y = containing_block.y - (box.GetSize(BoxArea::Margin).y + ResolveValue(computed.bottom(), containing_block.y));
  524. // Add the margin edge to the position, since inset properties (top/right/bottom/left) set the margin edge
  525. // position, while offsets use the border edge.
  526. position.x += box.GetEdge(BoxArea::Margin, BoxEdge::Left);
  527. position.y += box.GetEdge(BoxArea::Margin, BoxEdge::Top);
  528. SetOffset(position, nullptr);
  529. }
  530. }
  531. void ElementDocument::DirtyPosition()
  532. {
  533. position_dirty = true;
  534. }
  535. void ElementDocument::DirtyDocumentLayout()
  536. {
  537. // Log::Message(Log::LT_INFO, "DirtyDocumentLayout: %s", GetAddress().c_str());
  538. layout_dirty = true;
  539. }
  540. void ElementDocument::DirtyVwAndVhProperties()
  541. {
  542. GetStyle()->DirtyPropertiesWithUnitsRecursive(Unit::VW | Unit::VH);
  543. }
  544. void ElementDocument::OnPropertyChange(const PropertyIdSet& changed_properties)
  545. {
  546. Element::OnPropertyChange(changed_properties);
  547. // If the document's font-size has been changed, we need to dirty all rem properties.
  548. if (changed_properties.Contains(PropertyId::FontSize))
  549. GetStyle()->DirtyPropertiesWithUnitsRecursive(Unit::REM);
  550. if (changed_properties.Contains(PropertyId::Top) || //
  551. changed_properties.Contains(PropertyId::Right) || //
  552. changed_properties.Contains(PropertyId::Bottom) || //
  553. changed_properties.Contains(PropertyId::Left))
  554. DirtyPosition();
  555. }
  556. void ElementDocument::ProcessDefaultAction(Event& event)
  557. {
  558. Element::ProcessDefaultAction(event);
  559. // Process generic keyboard events for this window in bubble phase
  560. if (event == EventId::Keydown)
  561. {
  562. int key_identifier = event.GetParameter<int>("key_identifier", Input::KI_UNKNOWN);
  563. // Process TAB
  564. if (key_identifier == Input::KI_TAB)
  565. {
  566. if (Element* element = FindNextTabElement(event.GetTargetElement(), !event.GetParameter<bool>("shift_key", false)))
  567. {
  568. if (element->Focus(true))
  569. {
  570. element->ScrollIntoView(ScrollAlignment::Nearest);
  571. event.StopPropagation();
  572. }
  573. }
  574. }
  575. // Process direction keys
  576. else if (key_identifier == Input::KI_LEFT || key_identifier == Input::KI_RIGHT || key_identifier == Input::KI_UP ||
  577. key_identifier == Input::KI_DOWN)
  578. {
  579. NavigationSearchDirection direction = {};
  580. PropertyId property_id = PropertyId::NavLeft;
  581. switch (key_identifier)
  582. {
  583. case Input::KI_LEFT:
  584. direction = NavigationSearchDirection::Left;
  585. property_id = PropertyId::NavLeft;
  586. break;
  587. case Input::KI_RIGHT:
  588. direction = NavigationSearchDirection::Right;
  589. property_id = PropertyId::NavRight;
  590. break;
  591. case Input::KI_UP:
  592. direction = NavigationSearchDirection::Up;
  593. property_id = PropertyId::NavUp;
  594. break;
  595. case Input::KI_DOWN:
  596. direction = NavigationSearchDirection::Down;
  597. property_id = PropertyId::NavDown;
  598. break;
  599. }
  600. auto GetNearestFocusable = [this](Element* focus_node) -> Element* {
  601. while (focus_node)
  602. {
  603. if (CanFocusElement(focus_node) == CanFocus::Yes)
  604. break;
  605. focus_node = focus_node->GetParentNode();
  606. }
  607. return focus_node ? focus_node : this;
  608. };
  609. Element* focus_node = GetNearestFocusable(GetFocusLeafNode());
  610. if (const Property* nav_property = focus_node->GetLocalProperty(property_id))
  611. {
  612. if (Element* next = FindNextNavigationElement(focus_node, direction, *nav_property))
  613. {
  614. if (next->Focus(true))
  615. {
  616. next->ScrollIntoView(ScrollAlignment::Nearest);
  617. event.StopPropagation();
  618. }
  619. }
  620. }
  621. }
  622. // Process ENTER being pressed on a focusable object (emulate click)
  623. else if (key_identifier == Input::KI_RETURN || key_identifier == Input::KI_NUMPADENTER || key_identifier == Input::KI_SPACE)
  624. {
  625. Element* focus_node = GetFocusLeafNode();
  626. if (focus_node && focus_node->GetComputedValues().tab_index() == Style::TabIndex::Auto)
  627. {
  628. focus_node->Click();
  629. event.StopPropagation();
  630. }
  631. }
  632. }
  633. }
  634. void ElementDocument::OnResize()
  635. {
  636. DirtyPosition();
  637. }
  638. bool ElementDocument::IsFocusableFromModal() const
  639. {
  640. return focusable_from_modal && IsVisible();
  641. }
  642. void ElementDocument::SetFocusableFromModal(bool focusable)
  643. {
  644. focusable_from_modal = focusable;
  645. }
  646. Element* ElementDocument::FindNextTabElement(Element* current_element, bool forward)
  647. {
  648. // This algorithm is quite sneaky, I originally thought a depth first search would work, but it appears not. What is
  649. // required is to cut the tree in half along the nodes from current_element up the root and then either traverse the
  650. // tree in a clockwise or anticlock wise direction depending if you're searching forward or backward respectively.
  651. // If we're searching forward, check the immediate children of this node first off.
  652. if (forward)
  653. {
  654. for (int i = 0; i < current_element->GetNumChildren(); i++)
  655. if (Element* result = SearchFocusSubtree(current_element->GetChild(i), forward))
  656. return result;
  657. }
  658. // Now walk up the tree, testing either the bottom or top
  659. // of the tree, depending on whether we're going forward
  660. // or backward respectively.
  661. bool search_enabled = false;
  662. Element* document = current_element->GetOwnerDocument();
  663. Element* child = current_element;
  664. Element* parent = current_element->GetParentNode();
  665. while (child != document)
  666. {
  667. const int num_children = parent->GetNumChildren();
  668. for (int i = 0; i < num_children; i++)
  669. {
  670. // Calculate index into children
  671. const int child_index = forward ? i : (num_children - i - 1);
  672. Element* search_child = parent->GetChild(child_index);
  673. // Do a search if its enabled
  674. if (search_enabled)
  675. if (Element* result = SearchFocusSubtree(search_child, forward))
  676. return result;
  677. // Enable searching when we reach the child.
  678. if (search_child == child)
  679. search_enabled = true;
  680. }
  681. // Advance up the tree
  682. child = parent;
  683. parent = parent->GetParentNode();
  684. search_enabled = false;
  685. }
  686. // We could not find anything to focus along this direction.
  687. // If we can focus the document, then focus that now.
  688. if (current_element != document && CanFocusElement(document) == CanFocus::Yes)
  689. return document;
  690. // Otherwise, search the entire document tree. This way we will wrap around.
  691. const int num_children = document->GetNumChildren();
  692. for (int i = 0; i < num_children; i++)
  693. {
  694. const int child_index = forward ? i : (num_children - i - 1);
  695. if (Element* result = SearchFocusSubtree(document->GetChild(child_index), forward))
  696. return result;
  697. }
  698. return nullptr;
  699. }
  700. Element* ElementDocument::SearchFocusSubtree(Element* element, bool forward)
  701. {
  702. CanFocus can_focus = CanFocusElement(element);
  703. if (can_focus == CanFocus::Yes)
  704. return element;
  705. else if (can_focus == CanFocus::NoAndNoChildren)
  706. return nullptr;
  707. for (int i = 0; i < element->GetNumChildren(); i++)
  708. {
  709. int child_index = i;
  710. if (!forward)
  711. child_index = element->GetNumChildren() - i - 1;
  712. if (Element* result = SearchFocusSubtree(element->GetChild(child_index), forward))
  713. return result;
  714. }
  715. return nullptr;
  716. }
  717. Element* ElementDocument::FindNextNavigationElement(Element* current_element, NavigationSearchDirection direction, const Property& property)
  718. {
  719. switch (property.unit)
  720. {
  721. case Unit::STRING:
  722. {
  723. const PropertySource* source = property.source.get();
  724. const String value = property.Get<String>();
  725. if (value[0] != '#')
  726. {
  727. Log::Message(Log::LT_WARNING,
  728. "Invalid navigation value '%s': Expected a keyword or a string with an element id prefixed with '#'. Declared at %s:%d",
  729. value.c_str(), source ? source->path.c_str() : "", source ? source->line_number : -1);
  730. return nullptr;
  731. }
  732. const String id = String(value.begin() + 1, value.end());
  733. Element* result = GetElementById(id);
  734. if (!result)
  735. {
  736. Log::Message(Log::LT_WARNING, "Trying to navigate to element with id '%s', but could not find element. Declared at %s:%d", id.c_str(),
  737. source ? source->path.c_str() : "", source ? source->line_number : -1);
  738. }
  739. return result;
  740. }
  741. break;
  742. case Unit::KEYWORD:
  743. {
  744. const bool direction_is_horizontal = (direction == NavigationSearchDirection::Left || direction == NavigationSearchDirection::Right);
  745. const bool direction_is_vertical = (direction == NavigationSearchDirection::Up || direction == NavigationSearchDirection::Down);
  746. switch (static_cast<Style::Nav>(property.value.Get<int>()))
  747. {
  748. case Style::Nav::None: return nullptr;
  749. case Style::Nav::Auto: break;
  750. case Style::Nav::Horizontal:
  751. if (!direction_is_horizontal)
  752. return nullptr;
  753. break;
  754. case Style::Nav::Vertical:
  755. if (!direction_is_vertical)
  756. return nullptr;
  757. break;
  758. }
  759. }
  760. break;
  761. default: return nullptr;
  762. }
  763. if (current_element == this)
  764. {
  765. const bool direction_is_forward = (direction == NavigationSearchDirection::Down || direction == NavigationSearchDirection::Right);
  766. return FindNextTabElement(this, direction_is_forward);
  767. }
  768. const Vector2f position = current_element->GetAbsoluteOffset(BoxArea::Border);
  769. const BoundingBox bounding_box = {position, position + current_element->GetBox().GetSize(BoxArea::Border)};
  770. auto GetNearestScrollContainer = [this](Element* element) -> Element* {
  771. for (element = element->GetParentNode(); element; element = element->GetParentNode())
  772. {
  773. if (IsScrollContainer(element))
  774. return element;
  775. }
  776. return this;
  777. };
  778. Element* start_element = GetNearestScrollContainer(current_element);
  779. SearchNavigationResult best_result;
  780. SearchNavigationTarget(best_result, start_element, direction, bounding_box, current_element);
  781. return best_result.element;
  782. }
  783. } // namespace Rml