ElementDocument.cpp 24 KB

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