Element.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561
  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/Element.h"
  30. #include "../../Include/RmlUi/Core/Dictionary.h"
  31. #include "../../Include/RmlUi/Core/PropertyIdSet.h"
  32. #include "../../Include/RmlUi/Core/TransformPrimitive.h"
  33. #include "../../Include/RmlUi/Core/TransformState.h"
  34. #include <algorithm>
  35. #include <limits>
  36. #include "Clock.h"
  37. #include "ComputeProperty.h"
  38. #include "ElementAnimation.h"
  39. #include "ElementBackground.h"
  40. #include "ElementBorder.h"
  41. #include "ElementDefinition.h"
  42. #include "ElementStyle.h"
  43. #include "EventDispatcher.h"
  44. #include "EventSpecification.h"
  45. #include "ElementDecoration.h"
  46. #include "LayoutEngine.h"
  47. #include "PluginRegistry.h"
  48. #include "PropertiesIterator.h"
  49. #include "Pool.h"
  50. #include "StyleSheetParser.h"
  51. #include "XMLParseTools.h"
  52. #include "../../Include/RmlUi/Core/Core.h"
  53. namespace Rml {
  54. namespace Core {
  55. /**
  56. STL function object for sorting elements by z-type (ie, float-types before general types, etc).
  57. @author Peter Curry
  58. */
  59. class ElementSortZOrder
  60. {
  61. public:
  62. bool operator()(const std::pair< Element*, float >& lhs, const std::pair< Element*, float >& rhs) const
  63. {
  64. return lhs.second < rhs.second;
  65. }
  66. };
  67. /**
  68. STL function object for sorting elements by z-index property.
  69. @author Peter Curry
  70. */
  71. class ElementSortZIndex
  72. {
  73. public:
  74. bool operator()(const Element* lhs, const Element* rhs) const
  75. {
  76. // Check the z-index.
  77. return lhs->GetZIndex() < rhs->GetZIndex();
  78. }
  79. };
  80. // Determines how many levels up in the hierarchy the OnChildAdd and OnChildRemove are called (starting at the child itself)
  81. static constexpr int ChildNotifyLevels = 2;
  82. // Meta objects for element collected in a single struct to reduce memory allocations
  83. struct ElementMeta
  84. {
  85. ElementMeta(Element* el) : event_dispatcher(el), style(el), background(el), border(el), decoration(el), scroll(el) {}
  86. EventDispatcher event_dispatcher;
  87. ElementStyle style;
  88. ElementBackground background;
  89. ElementBorder border;
  90. ElementDecoration decoration;
  91. ElementScroll scroll;
  92. Style::ComputedValues computed_values;
  93. };
  94. static Pool< ElementMeta > element_meta_chunk_pool(200, true);
  95. /// Constructs a new RmlUi element.
  96. Element::Element(const String& tag) : tag(tag), relative_offset_base(0, 0), relative_offset_position(0, 0), absolute_offset(0, 0), scroll_offset(0, 0), content_offset(0, 0), content_box(0, 0),
  97. transform_state(), dirty_transform(false), dirty_perspective(false), dirty_animation(false), dirty_transition(false)
  98. {
  99. RMLUI_ASSERT(tag == StringUtilities::ToLower(tag));
  100. parent = nullptr;
  101. focus = nullptr;
  102. instancer = nullptr;
  103. owner_document = nullptr;
  104. offset_fixed = false;
  105. offset_parent = nullptr;
  106. offset_dirty = true;
  107. client_area = Box::PADDING;
  108. num_non_dom_children = 0;
  109. visible = true;
  110. z_index = 0;
  111. local_stacking_context = false;
  112. local_stacking_context_forced = false;
  113. stacking_context_dirty = false;
  114. structure_dirty = false;
  115. computed_values_are_default_initialized = true;
  116. clipping_ignore_depth = 0;
  117. clipping_enabled = false;
  118. clipping_state_dirty = true;
  119. element_meta = element_meta_chunk_pool.AllocateAndConstruct(this);
  120. event_dispatcher = &element_meta->event_dispatcher;
  121. style = &element_meta->style;
  122. background = &element_meta->background;
  123. border = &element_meta->border;
  124. decoration = &element_meta->decoration;
  125. scroll = &element_meta->scroll;
  126. }
  127. Element::~Element()
  128. {
  129. RMLUI_ASSERT(parent == nullptr);
  130. PluginRegistry::NotifyElementDestroy(this);
  131. // Remove scrollbar elements before we delete the children!
  132. scroll->ClearScrollbars();
  133. // A simplified version of RemoveChild() for destruction.
  134. for (ElementPtr& child : children)
  135. {
  136. Element* child_ancestor = child.get();
  137. for (int i = 0; i <= ChildNotifyLevels && child_ancestor; i++, child_ancestor = child_ancestor->GetParentNode())
  138. child_ancestor->OnChildRemove(child.get());
  139. child->SetParent(nullptr);
  140. }
  141. children.clear();
  142. num_non_dom_children = 0;
  143. element_meta_chunk_pool.DestroyAndDeallocate(element_meta);
  144. }
  145. void Element::Update(float dp_ratio)
  146. {
  147. RMLUI_ZoneScoped;
  148. OnUpdate();
  149. UpdateStructure();
  150. UpdateTransition();
  151. UpdateAnimation();
  152. AdvanceAnimations();
  153. scroll->Update();
  154. UpdateProperties();
  155. for (size_t i = 0; i < children.size(); i++)
  156. children[i]->Update(dp_ratio);
  157. }
  158. void Element::UpdateProperties()
  159. {
  160. style->UpdateDefinition();
  161. if (style->AnyPropertiesDirty())
  162. {
  163. const ComputedValues* parent_values = nullptr;
  164. if (parent)
  165. parent_values = &parent->GetComputedValues();
  166. const ComputedValues* document_values = nullptr;
  167. float dp_ratio = 1.0f;
  168. if (auto doc = GetOwnerDocument())
  169. {
  170. document_values = &doc->GetComputedValues();
  171. if (Context * context = doc->GetContext())
  172. dp_ratio = context->GetDensityIndependentPixelRatio();
  173. }
  174. // Compute values and clear dirty properties
  175. PropertyIdSet dirty_properties = style->ComputeValues(element_meta->computed_values, parent_values, document_values, computed_values_are_default_initialized, dp_ratio);
  176. computed_values_are_default_initialized = false;
  177. // Computed values are just calculated and can safely be used in OnPropertyChange.
  178. // However, new properties set during this call will not be available until the next update loop.
  179. if (!dirty_properties.Empty())
  180. OnPropertyChange(dirty_properties);
  181. }
  182. }
  183. void Element::Render()
  184. {
  185. #ifdef RMLUI_ENABLE_PROFILING
  186. auto name = GetAddress(false, false);
  187. RMLUI_ZoneScoped;
  188. RMLUI_ZoneText(name.c_str(), name.size());
  189. #endif
  190. // Rebuild our stacking context if necessary.
  191. if (stacking_context_dirty)
  192. BuildLocalStackingContext();
  193. UpdateTransformState();
  194. // Apply our transform
  195. ElementUtilities::ApplyTransform(*this);
  196. // Render all elements in our local stacking context that have a z-index beneath our local index of 0.
  197. size_t i = 0;
  198. for (; i < stacking_context.size() && stacking_context[i]->z_index < 0; ++i)
  199. stacking_context[i]->Render();
  200. // Set up the clipping region for this element.
  201. if (ElementUtilities::SetClippingRegion(this))
  202. {
  203. background->RenderBackground();
  204. border->RenderBorder();
  205. decoration->RenderDecorators();
  206. {
  207. RMLUI_ZoneScopedNC("OnRender", 0x228B22);
  208. OnRender();
  209. }
  210. }
  211. // Render the rest of the elements in the stacking context.
  212. for (; i < stacking_context.size(); ++i)
  213. stacking_context[i]->Render();
  214. }
  215. // Clones this element, returning a new, unparented element.
  216. ElementPtr Element::Clone() const
  217. {
  218. ElementPtr clone;
  219. if (instancer)
  220. {
  221. clone = instancer->InstanceElement(nullptr, GetTagName(), attributes);
  222. if (clone)
  223. clone->SetInstancer(instancer);
  224. }
  225. else
  226. clone = Factory::InstanceElement(nullptr, GetTagName(), GetTagName(), attributes);
  227. if (clone != nullptr)
  228. {
  229. String inner_rml;
  230. GetInnerRML(inner_rml);
  231. clone->SetInnerRML(inner_rml);
  232. }
  233. return clone;
  234. }
  235. // Sets or removes a class on the element.
  236. void Element::SetClass(const String& class_name, bool activate)
  237. {
  238. style->SetClass(class_name, activate);
  239. }
  240. // Checks if a class is set on the element.
  241. bool Element::IsClassSet(const String& class_name) const
  242. {
  243. return style->IsClassSet(class_name);
  244. }
  245. // Specifies the entire list of classes for this element. This will replace any others specified.
  246. void Element::SetClassNames(const String& class_names)
  247. {
  248. SetAttribute("class", class_names);
  249. }
  250. /// Return the active class list
  251. String Element::GetClassNames() const
  252. {
  253. return style->GetClassNames();
  254. }
  255. // Returns the active style sheet for this element. This may be nullptr.
  256. const SharedPtr<StyleSheet>& Element::GetStyleSheet() const
  257. {
  258. if (ElementDocument * document = GetOwnerDocument())
  259. return document->GetStyleSheet();
  260. static SharedPtr<StyleSheet> null_style_sheet;
  261. return null_style_sheet;
  262. }
  263. // Returns the element's definition.
  264. const ElementDefinition* Element::GetDefinition()
  265. {
  266. return style->GetDefinition();
  267. }
  268. // Fills an String with the full address of this element.
  269. String Element::GetAddress(bool include_pseudo_classes, bool include_parents) const
  270. {
  271. // Add the tag name onto the address.
  272. String address(tag);
  273. // Add the ID if we have one.
  274. if (!id.empty())
  275. {
  276. address += "#";
  277. address += id;
  278. }
  279. String classes = style->GetClassNames();
  280. if (!classes.empty())
  281. {
  282. classes = StringUtilities::Replace(classes, ' ', '.');
  283. address += ".";
  284. address += classes;
  285. }
  286. if (include_pseudo_classes)
  287. {
  288. const PseudoClassList& pseudo_classes = style->GetActivePseudoClasses();
  289. for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
  290. {
  291. address += ":";
  292. address += (*i);
  293. }
  294. }
  295. if (include_parents && parent)
  296. {
  297. address += " < ";
  298. return address + parent->GetAddress(include_pseudo_classes, true);
  299. }
  300. else
  301. return address;
  302. }
  303. // Sets the position of this element, as a two-dimensional offset from another element.
  304. void Element::SetOffset(const Vector2f& offset, Element* _offset_parent, bool _offset_fixed)
  305. {
  306. _offset_fixed |= GetPosition() == Style::Position::Fixed;
  307. // If our offset has definitely changed, or any of our parenting has, then these are set and
  308. // updated based on our left / right / top / bottom properties.
  309. if (relative_offset_base != offset ||
  310. offset_parent != _offset_parent ||
  311. offset_fixed != _offset_fixed)
  312. {
  313. relative_offset_base = offset;
  314. offset_fixed = _offset_fixed;
  315. offset_parent = _offset_parent;
  316. UpdateOffset();
  317. DirtyOffset();
  318. }
  319. // Otherwise, our offset is updated in case left / right / top / bottom will have an impact on
  320. // our final position, and our children are dirtied if they do.
  321. else
  322. {
  323. Vector2f& old_base = relative_offset_base;
  324. Vector2f& old_position = relative_offset_position;
  325. UpdateOffset();
  326. if (old_base != relative_offset_base ||
  327. old_position != relative_offset_position)
  328. DirtyOffset();
  329. }
  330. }
  331. // Returns the position of the top-left corner of one of the areas of this element's primary box.
  332. Vector2f Element::GetRelativeOffset(Box::Area area)
  333. {
  334. return relative_offset_base + relative_offset_position + GetBox().GetPosition(area);
  335. }
  336. // Returns the position of the top-left corner of one of the areas of this element's primary box.
  337. Vector2f Element::GetAbsoluteOffset(Box::Area area)
  338. {
  339. if (offset_dirty)
  340. {
  341. offset_dirty = false;
  342. if (offset_parent != nullptr)
  343. absolute_offset = offset_parent->GetAbsoluteOffset(Box::BORDER) + relative_offset_base + relative_offset_position;
  344. else
  345. absolute_offset = relative_offset_base + relative_offset_position;
  346. // Add any parent scrolling onto our position as well. Could cache this if required.
  347. if (!offset_fixed)
  348. {
  349. Element* scroll_parent = parent;
  350. while (scroll_parent != nullptr)
  351. {
  352. absolute_offset -= (scroll_parent->scroll_offset + scroll_parent->content_offset);
  353. if (scroll_parent == offset_parent)
  354. break;
  355. else
  356. scroll_parent = scroll_parent->parent;
  357. }
  358. }
  359. }
  360. return absolute_offset + GetBox().GetPosition(area);
  361. }
  362. // Sets an alternate area to use as the client area.
  363. void Element::SetClientArea(Box::Area _client_area)
  364. {
  365. client_area = _client_area;
  366. }
  367. // Returns the area the element uses as its client area.
  368. Box::Area Element::GetClientArea() const
  369. {
  370. return client_area;
  371. }
  372. // Sets the dimensions of the element's internal content.
  373. void Element::SetContentBox(const Vector2f& _content_offset, const Vector2f& _content_box)
  374. {
  375. if (content_offset != _content_offset ||
  376. content_box != _content_box)
  377. {
  378. // Seems to be jittering a wee bit; might need to be looked at.
  379. scroll_offset.x += (content_offset.x - _content_offset.x);
  380. scroll_offset.y += (content_offset.y - _content_offset.y);
  381. content_offset = _content_offset;
  382. content_box = _content_box;
  383. scroll_offset.x = Math::Min(scroll_offset.x, GetScrollWidth() - GetClientWidth());
  384. scroll_offset.y = Math::Min(scroll_offset.y, GetScrollHeight() - GetClientHeight());
  385. DirtyOffset();
  386. }
  387. }
  388. // Sets the box describing the size of the element.
  389. void Element::SetBox(const Box& box)
  390. {
  391. if (box != main_box || additional_boxes.size() > 0)
  392. {
  393. main_box = box;
  394. additional_boxes.clear();
  395. OnResize();
  396. background->DirtyBackground();
  397. border->DirtyBorder();
  398. decoration->DirtyDecorators();
  399. }
  400. }
  401. // Adds a box to the end of the list describing this element's geometry.
  402. void Element::AddBox(const Box& box)
  403. {
  404. additional_boxes.push_back(box);
  405. OnResize();
  406. background->DirtyBackground();
  407. border->DirtyBorder();
  408. decoration->DirtyDecorators();
  409. }
  410. // Returns one of the boxes describing the size of the element.
  411. const Box& Element::GetBox()
  412. {
  413. return main_box;
  414. }
  415. // Returns one of the boxes describing the size of the element.
  416. const Box& Element::GetBox(int index)
  417. {
  418. if (index < 1)
  419. return main_box;
  420. int additional_box_index = index - 1;
  421. if (additional_box_index >= (int)additional_boxes.size())
  422. return main_box;
  423. return additional_boxes[additional_box_index];
  424. }
  425. // Returns the number of boxes making up this element's geometry.
  426. int Element::GetNumBoxes()
  427. {
  428. return 1 + (int)additional_boxes.size();
  429. }
  430. // Returns the baseline of the element, in pixels offset from the bottom of the element's content area.
  431. float Element::GetBaseline() const
  432. {
  433. return 0;
  434. }
  435. // Gets the intrinsic dimensions of this element, if it is of a type that has an inherent size.
  436. bool Element::GetIntrinsicDimensions(Vector2f& RMLUI_UNUSED_PARAMETER(dimensions))
  437. {
  438. RMLUI_UNUSED(dimensions);
  439. return false;
  440. }
  441. // Checks if a given point in screen coordinates lies within the bordered area of this element.
  442. bool Element::IsPointWithinElement(const Vector2f& point)
  443. {
  444. Vector2f position = GetAbsoluteOffset(Box::BORDER);
  445. for (int i = 0; i < GetNumBoxes(); ++i)
  446. {
  447. const Box& box = GetBox(i);
  448. Vector2f box_position = position + box.GetOffset();
  449. Vector2f box_dimensions = box.GetSize(Box::BORDER);
  450. if (point.x >= box_position.x &&
  451. point.x <= (box_position.x + box_dimensions.x) &&
  452. point.y >= box_position.y &&
  453. point.y <= (box_position.y + box_dimensions.y))
  454. {
  455. return true;
  456. }
  457. }
  458. return false;
  459. }
  460. // Returns the visibility of the element.
  461. bool Element::IsVisible() const
  462. {
  463. return visible;
  464. }
  465. // Returns the z-index of the element.
  466. float Element::GetZIndex() const
  467. {
  468. return z_index;
  469. }
  470. // Returns the element's font face handle.
  471. FontFaceHandle Element::GetFontFaceHandle() const
  472. {
  473. return element_meta->computed_values.font_face_handle;
  474. }
  475. // Sets a local property override on the element.
  476. bool Element::SetProperty(const String& name, const String& value)
  477. {
  478. // The name may be a shorthand giving us multiple underlying properties
  479. PropertyDictionary properties;
  480. if (!StyleSheetSpecification::ParsePropertyDeclaration(properties, name, value))
  481. {
  482. Log::Message(Log::LT_WARNING, "Syntax error parsing inline property declaration '%s: %s;'.", name.c_str(), value.c_str());
  483. return false;
  484. }
  485. for (auto& property : properties.GetProperties())
  486. {
  487. if (!style->SetProperty(property.first, property.second))
  488. return false;
  489. }
  490. return true;
  491. }
  492. // Sets a local property override on the element to a pre-parsed value.
  493. bool Element::SetProperty(PropertyId id, const Property& property)
  494. {
  495. return style->SetProperty(id, property);
  496. }
  497. // Removes a local property override on the element.
  498. void Element::RemoveProperty(const String& name)
  499. {
  500. style->RemoveProperty(StyleSheetSpecification::GetPropertyId(name));
  501. }
  502. // Removes a local property override on the element.
  503. void Element::RemoveProperty(PropertyId id)
  504. {
  505. style->RemoveProperty(id);
  506. }
  507. // Returns one of this element's properties.
  508. const Property* Element::GetProperty(const String& name)
  509. {
  510. return style->GetProperty(StyleSheetSpecification::GetPropertyId(name));
  511. }
  512. // Returns one of this element's properties.
  513. const Property* Element::GetProperty(PropertyId id)
  514. {
  515. return style->GetProperty(id);
  516. }
  517. // Returns one of this element's properties.
  518. const Property* Element::GetLocalProperty(const String& name)
  519. {
  520. return style->GetLocalProperty(StyleSheetSpecification::GetPropertyId(name));
  521. }
  522. const Property* Element::GetLocalProperty(PropertyId id)
  523. {
  524. return style->GetLocalProperty(id);
  525. }
  526. const PropertyMap& Element::GetLocalStyleProperties()
  527. {
  528. return style->GetLocalStyleProperties();
  529. }
  530. float Element::ResolveNumericProperty(const Property *property, float base_value)
  531. {
  532. return style->ResolveNumericProperty(property, base_value);
  533. }
  534. float Element::ResolveNumericProperty(const String& property_name)
  535. {
  536. auto property = style->GetProperty(StyleSheetSpecification::GetPropertyId(property_name));
  537. if (!property)
  538. return 0.0f;
  539. if (property->unit & Property::ANGLE)
  540. return ComputeAngle(*property);
  541. RelativeTarget relative_target = RelativeTarget::None;
  542. if (property->definition)
  543. relative_target = property->definition->GetRelativeTarget();
  544. float result = style->ResolveLength(property, relative_target);
  545. return result;
  546. }
  547. Vector2f Element::GetContainingBlock()
  548. {
  549. Vector2f containing_block(0, 0);
  550. if (offset_parent != nullptr)
  551. {
  552. using namespace Style;
  553. Position position_property = GetPosition();
  554. const Box& parent_box = offset_parent->GetBox();
  555. if (position_property == Position::Static || position_property == Position::Relative)
  556. {
  557. containing_block = parent_box.GetSize();
  558. }
  559. else if(position_property == Position::Absolute || position_property == Position::Fixed)
  560. {
  561. containing_block = parent_box.GetSize(Box::PADDING);
  562. }
  563. }
  564. return containing_block;
  565. }
  566. Style::Position Element::GetPosition()
  567. {
  568. return element_meta->computed_values.position;
  569. }
  570. Style::Float Element::GetFloat()
  571. {
  572. return element_meta->computed_values.float_;
  573. }
  574. Style::Display Element::GetDisplay()
  575. {
  576. return element_meta->computed_values.display;
  577. }
  578. float Element::GetLineHeight()
  579. {
  580. return element_meta->computed_values.line_height.value;
  581. }
  582. // Returns this element's TransformState
  583. const TransformState *Element::GetTransformState() const noexcept
  584. {
  585. return transform_state.get();
  586. }
  587. // Project a 2D point in pixel coordinates onto the element's plane.
  588. bool Element::Project(Vector2f& point) const noexcept
  589. {
  590. if(!transform_state || !transform_state->GetTransform())
  591. return true;
  592. // The input point is in window coordinates. Need to find the projection of the point onto the current element plane,
  593. // taking into account the full transform applied to the element.
  594. if (const Matrix4f* inv_transform = transform_state->GetInverseTransform())
  595. {
  596. // Pick two points forming a line segment perpendicular to the window.
  597. Vector4f window_points[2] = {{ point.x, point.y, -10, 1}, { point.x, point.y, 10, 1 }};
  598. // Project them into the local element space.
  599. window_points[0] = *inv_transform * window_points[0];
  600. window_points[1] = *inv_transform * window_points[1];
  601. Vector3f local_points[2] = {
  602. window_points[0].PerspectiveDivide(),
  603. window_points[1].PerspectiveDivide()
  604. };
  605. // Construct a ray from the two projected points in the local space of the current element.
  606. // Find the intersection with the z=0 plane to produce our destination point.
  607. Vector3f ray = local_points[1] - local_points[0];
  608. // Only continue if we are not close to parallel with the plane.
  609. if(std::abs(ray.z) > 1.0f)
  610. {
  611. // Solving the line equation p = p0 + t*ray for t, knowing that p.z = 0, produces the following.
  612. float t = -local_points[0].z / ray.z;
  613. Vector3f p = local_points[0] + ray * t;
  614. point = Vector2f(p.x, p.y);
  615. return true;
  616. }
  617. }
  618. // The transformation matrix is either singular, or the ray is parallel to the element's plane.
  619. return false;
  620. }
  621. PropertiesIteratorView Element::IterateLocalProperties() const
  622. {
  623. return PropertiesIteratorView(std::make_unique<PropertiesIterator>(style->Iterate()));
  624. }
  625. // Sets or removes a pseudo-class on the element.
  626. void Element::SetPseudoClass(const String& pseudo_class, bool activate)
  627. {
  628. style->SetPseudoClass(pseudo_class, activate);
  629. }
  630. // Checks if a specific pseudo-class has been set on the element.
  631. bool Element::IsPseudoClassSet(const String& pseudo_class) const
  632. {
  633. return style->IsPseudoClassSet(pseudo_class);
  634. }
  635. // Checks if a complete set of pseudo-classes are set on the element.
  636. bool Element::ArePseudoClassesSet(const PseudoClassList& pseudo_classes) const
  637. {
  638. for (PseudoClassList::const_iterator i = pseudo_classes.begin(); i != pseudo_classes.end(); ++i)
  639. {
  640. if (!IsPseudoClassSet(*i))
  641. return false;
  642. }
  643. return true;
  644. }
  645. // Gets a list of the current active pseudo classes
  646. const PseudoClassList& Element::GetActivePseudoClasses() const
  647. {
  648. return style->GetActivePseudoClasses();
  649. }
  650. /// Get the named attribute
  651. Variant* Element::GetAttribute(const String& name)
  652. {
  653. return GetIf(attributes, name);
  654. }
  655. // Checks if the element has a certain attribute.
  656. bool Element::HasAttribute(const String& name) const
  657. {
  658. return attributes.find(name) != attributes.end();
  659. }
  660. // Removes an attribute from the element
  661. void Element::RemoveAttribute(const String& name)
  662. {
  663. auto it = attributes.find(name);
  664. if (it != attributes.end())
  665. {
  666. attributes.erase(it);
  667. ElementAttributes changed_attributes;
  668. changed_attributes.emplace(name, Variant());
  669. OnAttributeChange(changed_attributes);
  670. }
  671. }
  672. // Gets the outer most focus element down the tree from this node
  673. Element* Element::GetFocusLeafNode()
  674. {
  675. // If there isn't a focus, then we are the leaf.
  676. if (!focus)
  677. {
  678. return this;
  679. }
  680. // Recurse down the tree until we found the leaf focus element
  681. Element* focus_element = focus;
  682. while (focus_element->focus)
  683. focus_element = focus_element->focus;
  684. return focus_element;
  685. }
  686. // Returns the element's context.
  687. Context* Element::GetContext() const
  688. {
  689. ElementDocument* document = GetOwnerDocument();
  690. if (document != nullptr)
  691. return document->GetContext();
  692. return nullptr;
  693. }
  694. // Set a group of attributes
  695. void Element::SetAttributes(const ElementAttributes& _attributes)
  696. {
  697. attributes.reserve(attributes.size() + _attributes.size());
  698. for (auto& pair : _attributes)
  699. attributes[pair.first] = pair.second;
  700. OnAttributeChange(_attributes);
  701. }
  702. // Returns the number of attributes on the element.
  703. int Element::GetNumAttributes() const
  704. {
  705. return (int)attributes.size();
  706. }
  707. // Gets the name of the element.
  708. const String& Element::GetTagName() const
  709. {
  710. return tag;
  711. }
  712. // Gets the ID of the element.
  713. const String& Element::GetId() const
  714. {
  715. return id;
  716. }
  717. // Sets the ID of the element.
  718. void Element::SetId(const String& _id)
  719. {
  720. SetAttribute("id", _id);
  721. }
  722. // Gets the horizontal offset from the context's left edge to element's left border edge.
  723. float Element::GetAbsoluteLeft()
  724. {
  725. return GetAbsoluteOffset(Box::BORDER).x;
  726. }
  727. // Gets the vertical offset from the context's top edge to element's top border edge.
  728. float Element::GetAbsoluteTop()
  729. {
  730. return GetAbsoluteOffset(Box::BORDER).y;
  731. }
  732. // Gets the width of the left border of an element.
  733. float Element::GetClientLeft()
  734. {
  735. return GetBox().GetPosition(client_area).x;
  736. }
  737. // Gets the height of the top border of an element.
  738. float Element::GetClientTop()
  739. {
  740. return GetBox().GetPosition(client_area).y;
  741. }
  742. // Gets the inner width of the element.
  743. float Element::GetClientWidth()
  744. {
  745. return GetBox().GetSize(client_area).x - scroll->GetScrollbarSize(ElementScroll::VERTICAL);
  746. }
  747. // Gets the inner height of the element.
  748. float Element::GetClientHeight()
  749. {
  750. return GetBox().GetSize(client_area).y - scroll->GetScrollbarSize(ElementScroll::HORIZONTAL);
  751. }
  752. // Returns the element from which all offset calculations are currently computed.
  753. Element* Element::GetOffsetParent()
  754. {
  755. return offset_parent;
  756. }
  757. // Gets the distance from this element's left border to its offset parent's left border.
  758. float Element::GetOffsetLeft()
  759. {
  760. return relative_offset_base.x + relative_offset_position.x;
  761. }
  762. // Gets the distance from this element's top border to its offset parent's top border.
  763. float Element::GetOffsetTop()
  764. {
  765. return relative_offset_base.y + relative_offset_position.y;
  766. }
  767. // Gets the width of the element, including the client area, padding, borders and scrollbars, but not margins.
  768. float Element::GetOffsetWidth()
  769. {
  770. return GetBox().GetSize(Box::BORDER).x;
  771. }
  772. // Gets the height of the element, including the client area, padding, borders and scrollbars, but not margins.
  773. float Element::GetOffsetHeight()
  774. {
  775. return GetBox().GetSize(Box::BORDER).y;
  776. }
  777. // Gets the left scroll offset of the element.
  778. float Element::GetScrollLeft()
  779. {
  780. return scroll_offset.x;
  781. }
  782. // Sets the left scroll offset of the element.
  783. void Element::SetScrollLeft(float scroll_left)
  784. {
  785. const float new_offset = Math::Clamp(scroll_left, 0.0f, GetScrollWidth() - GetClientWidth());
  786. if (new_offset != scroll_offset.x)
  787. {
  788. scroll_offset.x = new_offset;
  789. scroll->UpdateScrollbar(ElementScroll::HORIZONTAL);
  790. DirtyOffset();
  791. DispatchEvent(EventId::Scroll, Dictionary());
  792. }
  793. }
  794. // Gets the top scroll offset of the element.
  795. float Element::GetScrollTop()
  796. {
  797. return scroll_offset.y;
  798. }
  799. // Sets the top scroll offset of the element.
  800. void Element::SetScrollTop(float scroll_top)
  801. {
  802. const float new_offset = Math::Clamp(scroll_top, 0.0f, GetScrollHeight() - GetClientHeight());
  803. if(new_offset != scroll_offset.y)
  804. {
  805. scroll_offset.y = new_offset;
  806. scroll->UpdateScrollbar(ElementScroll::VERTICAL);
  807. DirtyOffset();
  808. DispatchEvent(EventId::Scroll, Dictionary());
  809. }
  810. }
  811. // Gets the width of the scrollable content of the element; it includes the element padding but not its margin.
  812. float Element::GetScrollWidth()
  813. {
  814. return Math::Max(content_box.x, GetClientWidth());
  815. }
  816. // Gets the height of the scrollable content of the element; it includes the element padding but not its margin.
  817. float Element::GetScrollHeight()
  818. {
  819. return Math::Max(content_box.y, GetClientHeight());
  820. }
  821. // Gets the object representing the declarations of an element's style attributes.
  822. ElementStyle* Element::GetStyle() const
  823. {
  824. return style;
  825. }
  826. // Gets the document this element belongs to.
  827. ElementDocument* Element::GetOwnerDocument() const
  828. {
  829. #ifdef RMLUI_DEBUG
  830. if (parent && !owner_document)
  831. {
  832. // Since we have a parent but no owner_document, then we must be a 'loose' element -- that is, constructed
  833. // outside of a document and not attached to a child of any element in the hierarchy of a document.
  834. // This check ensures that we didn't just forget to set the owner document.
  835. RMLUI_ASSERT(!parent->GetOwnerDocument());
  836. }
  837. #endif
  838. return owner_document;
  839. }
  840. // Gets this element's parent node.
  841. Element* Element::GetParentNode() const
  842. {
  843. return parent;
  844. }
  845. // Gets the element immediately following this one in the tree.
  846. Element* Element::GetNextSibling() const
  847. {
  848. if (parent == nullptr)
  849. return nullptr;
  850. for (size_t i = 0; i < parent->children.size() - (parent->num_non_dom_children + 1); i++)
  851. {
  852. if (parent->children[i].get() == this)
  853. return parent->children[i + 1].get();
  854. }
  855. return nullptr;
  856. }
  857. // Gets the element immediately preceding this one in the tree.
  858. Element* Element::GetPreviousSibling() const
  859. {
  860. if (parent == nullptr)
  861. return nullptr;
  862. for (size_t i = 1; i < parent->children.size() - parent->num_non_dom_children; i++)
  863. {
  864. if (parent->children[i].get() == this)
  865. return parent->children[i - 1].get();
  866. }
  867. return nullptr;
  868. }
  869. // Returns the first child of this element.
  870. Element* Element::GetFirstChild() const
  871. {
  872. if (GetNumChildren() > 0)
  873. return children[0].get();
  874. return nullptr;
  875. }
  876. // Gets the last child of this element.
  877. Element* Element::GetLastChild() const
  878. {
  879. if (GetNumChildren() > 0)
  880. return (children.end() - (num_non_dom_children + 1))->get();
  881. return nullptr;
  882. }
  883. Element* Element::GetChild(int index) const
  884. {
  885. if (index < 0 || index >= (int) children.size())
  886. return nullptr;
  887. return children[index].get();
  888. }
  889. int Element::GetNumChildren(bool include_non_dom_elements) const
  890. {
  891. return (int) children.size() - (include_non_dom_elements ? 0 : num_non_dom_children);
  892. }
  893. // Gets the markup and content of the element.
  894. void Element::GetInnerRML(String& content) const
  895. {
  896. for (int i = 0; i < GetNumChildren(); i++)
  897. {
  898. children[i]->GetRML(content);
  899. }
  900. }
  901. // Gets the markup and content of the element.
  902. String Element::GetInnerRML() const {
  903. String result;
  904. GetInnerRML(result);
  905. return result;
  906. }
  907. // Sets the markup and content of the element. All existing children will be replaced.
  908. void Element::SetInnerRML(const String& rml)
  909. {
  910. RMLUI_ZoneScopedC(0x6495ED);
  911. // Remove all DOM children.
  912. while ((int) children.size() > num_non_dom_children)
  913. RemoveChild(children.front().get());
  914. if(!rml.empty())
  915. Factory::InstanceElementText(this, rml);
  916. }
  917. // Sets the current element as the focus object.
  918. bool Element::Focus()
  919. {
  920. // Are we allowed focus?
  921. Style::Focus focus_property = element_meta->computed_values.focus;
  922. if (focus_property == Style::Focus::None)
  923. return false;
  924. // Ask our context if we can switch focus.
  925. Context* context = GetContext();
  926. if (context == nullptr)
  927. return false;
  928. if (!context->OnFocusChange(this))
  929. return false;
  930. // Set this as the end of the focus chain.
  931. focus = nullptr;
  932. // Update the focus chain up the hierarchy.
  933. Element* element = this;
  934. while (Element* parent = element->GetParentNode())
  935. {
  936. parent->focus = element;
  937. element = parent;
  938. }
  939. return true;
  940. }
  941. // Removes focus from from this element.
  942. void Element::Blur()
  943. {
  944. if (parent)
  945. {
  946. Context* context = GetContext();
  947. if (context == nullptr)
  948. return;
  949. if (context->GetFocusElement() == this)
  950. {
  951. parent->Focus();
  952. }
  953. else if (parent->focus == this)
  954. {
  955. parent->focus = nullptr;
  956. }
  957. }
  958. }
  959. // Fakes a mouse click on this element.
  960. void Element::Click()
  961. {
  962. Context* context = GetContext();
  963. if (context == nullptr)
  964. return;
  965. context->GenerateClickEvent(this);
  966. }
  967. // Adds an event listener
  968. void Element::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  969. {
  970. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  971. event_dispatcher->AttachEvent(id, listener, in_capture_phase);
  972. }
  973. // Adds an event listener
  974. void Element::AddEventListener(EventId id, EventListener* listener, bool in_capture_phase)
  975. {
  976. event_dispatcher->AttachEvent(id, listener, in_capture_phase);
  977. }
  978. // Removes an event listener from this element.
  979. void Element::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  980. {
  981. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  982. event_dispatcher->DetachEvent(id, listener, in_capture_phase);
  983. }
  984. // Removes an event listener from this element.
  985. void Element::RemoveEventListener(EventId id, EventListener* listener, bool in_capture_phase)
  986. {
  987. event_dispatcher->DetachEvent(id, listener, in_capture_phase);
  988. }
  989. // Dispatches the specified event
  990. bool Element::DispatchEvent(const String& type, const Dictionary& parameters)
  991. {
  992. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  993. return event_dispatcher->DispatchEvent(this, specification.id, type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
  994. }
  995. // Dispatches the specified event
  996. bool Element::DispatchEvent(const String& type, const Dictionary& parameters, bool interruptible, bool bubbles)
  997. {
  998. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  999. return event_dispatcher->DispatchEvent(this, specification.id, type, parameters, interruptible, bubbles, specification.default_action_phase);
  1000. }
  1001. // Dispatches the specified event
  1002. bool Element::DispatchEvent(EventId id, const Dictionary& parameters)
  1003. {
  1004. const EventSpecification& specification = EventSpecificationInterface::Get(id);
  1005. return event_dispatcher->DispatchEvent(this, specification.id, specification.type, parameters, specification.interruptible, specification.bubbles, specification.default_action_phase);
  1006. }
  1007. // Scrolls the parent element's contents so that this element is visible.
  1008. void Element::ScrollIntoView(bool align_with_top)
  1009. {
  1010. Vector2f size(0, 0);
  1011. if (!align_with_top)
  1012. {
  1013. size.y = main_box.GetOffset().y +
  1014. main_box.GetSize(Box::BORDER).y;
  1015. }
  1016. Element* scroll_parent = parent;
  1017. while (scroll_parent != nullptr)
  1018. {
  1019. Style::Overflow overflow_x_property = scroll_parent->GetComputedValues().overflow_x;
  1020. Style::Overflow overflow_y_property = scroll_parent->GetComputedValues().overflow_y;
  1021. if ((overflow_x_property != Style::Overflow::Visible &&
  1022. scroll_parent->GetScrollWidth() > scroll_parent->GetClientWidth()) ||
  1023. (overflow_y_property != Style::Overflow::Visible &&
  1024. scroll_parent->GetScrollHeight() > scroll_parent->GetClientHeight()))
  1025. {
  1026. Vector2f offset = scroll_parent->GetAbsoluteOffset(Box::BORDER) - GetAbsoluteOffset(Box::BORDER);
  1027. Vector2f scroll_offset(scroll_parent->GetScrollLeft(), scroll_parent->GetScrollTop());
  1028. scroll_offset -= offset;
  1029. scroll_offset.x += scroll_parent->GetClientLeft();
  1030. scroll_offset.y += scroll_parent->GetClientTop();
  1031. if (!align_with_top)
  1032. scroll_offset.y -= (scroll_parent->GetClientHeight() - size.y);
  1033. if (overflow_x_property != Style::Overflow::Visible)
  1034. scroll_parent->SetScrollLeft(scroll_offset.x);
  1035. if (overflow_y_property != Style::Overflow::Visible)
  1036. scroll_parent->SetScrollTop(scroll_offset.y);
  1037. }
  1038. scroll_parent = scroll_parent->GetParentNode();
  1039. }
  1040. }
  1041. // Appends a child to this element
  1042. Element* Element::AppendChild(ElementPtr child, bool dom_element)
  1043. {
  1044. RMLUI_ASSERT(child);
  1045. Element* child_ptr = child.get();
  1046. child_ptr->SetParent(this);
  1047. if (dom_element)
  1048. children.insert(children.end() - num_non_dom_children, std::move(child));
  1049. else
  1050. {
  1051. children.push_back(std::move(child));
  1052. num_non_dom_children++;
  1053. }
  1054. Element* ancestor = child_ptr;
  1055. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1056. ancestor->OnChildAdd(child_ptr);
  1057. DirtyStackingContext();
  1058. DirtyStructure();
  1059. if (dom_element)
  1060. DirtyLayout();
  1061. return child_ptr;
  1062. }
  1063. // Adds a child to this element, directly after the adjacent element. Inherits
  1064. // the dom/non-dom status from the adjacent element.
  1065. Element* Element::InsertBefore(ElementPtr child, Element* adjacent_element)
  1066. {
  1067. RMLUI_ASSERT(child);
  1068. // Find the position in the list of children of the adjacent element. If
  1069. // it's nullptr or we can't find it, then we insert it at the end of the dom
  1070. // children, as a dom element.
  1071. size_t child_index = 0;
  1072. bool found_child = false;
  1073. if (adjacent_element)
  1074. {
  1075. for (child_index = 0; child_index < children.size(); child_index++)
  1076. {
  1077. if (children[child_index].get() == adjacent_element)
  1078. {
  1079. found_child = true;
  1080. break;
  1081. }
  1082. }
  1083. }
  1084. Element* child_ptr = nullptr;
  1085. if (found_child)
  1086. {
  1087. child_ptr = child.get();
  1088. child_ptr->SetParent(this);
  1089. if ((int) child_index >= GetNumChildren())
  1090. num_non_dom_children++;
  1091. else
  1092. DirtyLayout();
  1093. children.insert(children.begin() + child_index, std::move(child));
  1094. Element* ancestor = child_ptr;
  1095. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1096. ancestor->OnChildAdd(child_ptr);
  1097. DirtyStackingContext();
  1098. DirtyStructure();
  1099. }
  1100. else
  1101. {
  1102. child_ptr = AppendChild(std::move(child));
  1103. }
  1104. return child_ptr;
  1105. }
  1106. // Replaces the second node with the first node.
  1107. ElementPtr Element::ReplaceChild(ElementPtr inserted_element, Element* replaced_element)
  1108. {
  1109. RMLUI_ASSERT(inserted_element);
  1110. auto insertion_point = children.begin();
  1111. while (insertion_point != children.end() && insertion_point->get() != replaced_element)
  1112. {
  1113. ++insertion_point;
  1114. }
  1115. Element* inserted_element_ptr = inserted_element.get();
  1116. if (insertion_point == children.end())
  1117. {
  1118. AppendChild(std::move(inserted_element));
  1119. return nullptr;
  1120. }
  1121. inserted_element_ptr->SetParent(this);
  1122. children.insert(insertion_point, std::move(inserted_element));
  1123. ElementPtr result = RemoveChild(replaced_element);
  1124. Element* ancestor = inserted_element_ptr;
  1125. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1126. ancestor->OnChildAdd(inserted_element_ptr);
  1127. return result;
  1128. }
  1129. // Removes the specified child
  1130. ElementPtr Element::RemoveChild(Element* child)
  1131. {
  1132. size_t child_index = 0;
  1133. for (auto itr = children.begin(); itr != children.end(); ++itr)
  1134. {
  1135. // Add the element to the delete list
  1136. if (itr->get() == child)
  1137. {
  1138. Element* ancestor = child;
  1139. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1140. ancestor->OnChildRemove(child);
  1141. if (child_index >= children.size() - num_non_dom_children)
  1142. num_non_dom_children--;
  1143. ElementPtr detached_child = std::move(*itr);
  1144. children.erase(itr);
  1145. // Remove the child element as the focused child of this element.
  1146. if (child == focus)
  1147. {
  1148. focus = nullptr;
  1149. // If this child (or a descendant of this child) is the context's currently
  1150. // focused element, set the focus to us instead.
  1151. if (Context * context = GetContext())
  1152. {
  1153. Element* focus_element = context->GetFocusElement();
  1154. while (focus_element)
  1155. {
  1156. if (focus_element == child)
  1157. {
  1158. Focus();
  1159. break;
  1160. }
  1161. focus_element = focus_element->GetParentNode();
  1162. }
  1163. }
  1164. }
  1165. detached_child->SetParent(nullptr);
  1166. DirtyLayout();
  1167. DirtyStackingContext();
  1168. DirtyStructure();
  1169. return detached_child;
  1170. }
  1171. child_index++;
  1172. }
  1173. return nullptr;
  1174. }
  1175. bool Element::HasChildNodes() const
  1176. {
  1177. return (int) children.size() > num_non_dom_children;
  1178. }
  1179. Element* Element::GetElementById(const String& id)
  1180. {
  1181. // Check for special-case tokens.
  1182. if (id == "#self")
  1183. return this;
  1184. else if (id == "#document")
  1185. return GetOwnerDocument();
  1186. else if (id == "#parent")
  1187. return this->parent;
  1188. else
  1189. {
  1190. Element* search_root = GetOwnerDocument();
  1191. if (search_root == nullptr)
  1192. search_root = this;
  1193. return ElementUtilities::GetElementById(search_root, id);
  1194. }
  1195. }
  1196. // Get all elements with the given tag.
  1197. void Element::GetElementsByTagName(ElementList& elements, const String& tag)
  1198. {
  1199. return ElementUtilities::GetElementsByTagName(elements, this, tag);
  1200. }
  1201. // Get all elements with the given class set on them.
  1202. void Element::GetElementsByClassName(ElementList& elements, const String& class_name)
  1203. {
  1204. return ElementUtilities::GetElementsByClassName(elements, this, class_name);
  1205. }
  1206. // Access the event dispatcher
  1207. EventDispatcher* Element::GetEventDispatcher() const
  1208. {
  1209. return event_dispatcher;
  1210. }
  1211. String Element::GetEventDispatcherSummary() const
  1212. {
  1213. return event_dispatcher->ToString();
  1214. }
  1215. // Access the element background.
  1216. ElementBackground* Element::GetElementBackground() const
  1217. {
  1218. return background;
  1219. }
  1220. // Access the element border.
  1221. ElementBorder* Element::GetElementBorder() const
  1222. {
  1223. return border;
  1224. }
  1225. // Access the element decorators
  1226. ElementDecoration* Element::GetElementDecoration() const
  1227. {
  1228. return decoration;
  1229. }
  1230. // Returns the element's scrollbar functionality.
  1231. ElementScroll* Element::GetElementScroll() const
  1232. {
  1233. return scroll;
  1234. }
  1235. int Element::GetClippingIgnoreDepth()
  1236. {
  1237. if (clipping_state_dirty)
  1238. {
  1239. IsClippingEnabled();
  1240. }
  1241. return clipping_ignore_depth;
  1242. }
  1243. bool Element::IsClippingEnabled()
  1244. {
  1245. if (clipping_state_dirty)
  1246. {
  1247. const auto& computed = GetComputedValues();
  1248. // Is clipping enabled for this element, yes unless both overlow properties are set to visible
  1249. clipping_enabled = computed.overflow_x != Style::Overflow::Visible
  1250. || computed.overflow_y != Style::Overflow::Visible;
  1251. // Get the clipping ignore depth from the clip property
  1252. clipping_ignore_depth = computed.clip.number;
  1253. clipping_state_dirty = false;
  1254. }
  1255. return clipping_enabled;
  1256. }
  1257. // Gets the render interface owned by this element's context.
  1258. RenderInterface* Element::GetRenderInterface()
  1259. {
  1260. if (Context* context = GetContext())
  1261. return context->GetRenderInterface();
  1262. return Rml::Core::GetRenderInterface();
  1263. }
  1264. void Element::SetInstancer(ElementInstancer* _instancer)
  1265. {
  1266. // Only record the first instancer being set as some instancers call other instancers to do their dirty work, in
  1267. // which case we don't want to update the lowest level instancer.
  1268. if (!instancer)
  1269. {
  1270. instancer = _instancer;
  1271. }
  1272. }
  1273. // Forces the element to generate a local stacking context, regardless of the value of its z-index property.
  1274. void Element::ForceLocalStackingContext()
  1275. {
  1276. local_stacking_context_forced = true;
  1277. local_stacking_context = true;
  1278. DirtyStackingContext();
  1279. }
  1280. // Called during the update loop after children are rendered.
  1281. void Element::OnUpdate()
  1282. {
  1283. }
  1284. // Called during render after backgrounds, borders, decorators, but before children, are rendered.
  1285. void Element::OnRender()
  1286. {
  1287. }
  1288. void Element::OnResize()
  1289. {
  1290. }
  1291. // Called during a layout operation, when the element is being positioned and sized.
  1292. void Element::OnLayout()
  1293. {
  1294. }
  1295. // Called when attributes on the element are changed.
  1296. void Element::OnAttributeChange(const ElementAttributes& changed_attributes)
  1297. {
  1298. auto it = changed_attributes.find("id");
  1299. if (it != changed_attributes.end())
  1300. {
  1301. id = it->second.Get<String>();
  1302. style->DirtyDefinition();
  1303. }
  1304. it = changed_attributes.find("class");
  1305. if (it != changed_attributes.end())
  1306. {
  1307. style->SetClassNames(it->second.Get<String>());
  1308. }
  1309. // Add any inline style declarations.
  1310. it = changed_attributes.find("style");
  1311. if (it != changed_attributes.end())
  1312. {
  1313. PropertyDictionary properties;
  1314. StyleSheetParser parser;
  1315. parser.ParseProperties(properties, it->second.Get<String>());
  1316. Rml::Core::PropertyMap property_map = properties.GetProperties();
  1317. for (Rml::Core::PropertyMap::iterator i = property_map.begin(); i != property_map.end(); ++i)
  1318. {
  1319. style->SetProperty((*i).first, (*i).second);
  1320. }
  1321. }
  1322. }
  1323. // Called when properties on the element are changed.
  1324. void Element::OnPropertyChange(const PropertyIdSet& changed_properties)
  1325. {
  1326. RMLUI_ZoneScoped;
  1327. if (!IsLayoutDirty())
  1328. {
  1329. // Force a relayout if any of the changed properties require it.
  1330. const PropertyIdSet changed_properties_forcing_layout = (changed_properties & StyleSheetSpecification::GetRegisteredPropertiesForcingLayout());
  1331. if(!changed_properties_forcing_layout.Empty())
  1332. DirtyLayout();
  1333. }
  1334. // Update the visibility.
  1335. if (changed_properties.Contains(PropertyId::Visibility) ||
  1336. changed_properties.Contains(PropertyId::Display))
  1337. {
  1338. bool new_visibility = (element_meta->computed_values.display != Style::Display::None && element_meta->computed_values.visibility == Style::Visibility::Visible);
  1339. if (visible != new_visibility)
  1340. {
  1341. visible = new_visibility;
  1342. if (parent != nullptr)
  1343. parent->DirtyStackingContext();
  1344. if (!visible)
  1345. Blur();
  1346. }
  1347. if (changed_properties.Contains(PropertyId::Display))
  1348. {
  1349. // Due to structural pseudo-classes, this may change the element definition in siblings and parent.
  1350. // However, the definitions will only be changed on the next update loop which may result in jarring behavior for one @frame.
  1351. // A possible workaround is to add the parent to a list of elements that need to be updated again.
  1352. if (parent != nullptr)
  1353. parent->DirtyStructure();
  1354. }
  1355. }
  1356. // Update the position.
  1357. if (changed_properties.Contains(PropertyId::Left) ||
  1358. changed_properties.Contains(PropertyId::Right) ||
  1359. changed_properties.Contains(PropertyId::Top) ||
  1360. changed_properties.Contains(PropertyId::Bottom))
  1361. {
  1362. // TODO: This should happen during/after layout, as the containing box is not properly defined yet. Off-by-one @frame issue.
  1363. UpdateOffset();
  1364. DirtyOffset();
  1365. }
  1366. // Update the z-index.
  1367. if (changed_properties.Contains(PropertyId::ZIndex))
  1368. {
  1369. Style::ZIndex z_index_property = element_meta->computed_values.z_index;
  1370. if (z_index_property.type == Style::ZIndex::Auto)
  1371. {
  1372. if (local_stacking_context &&
  1373. !local_stacking_context_forced)
  1374. {
  1375. // We're no longer acting as a stacking context.
  1376. local_stacking_context = false;
  1377. stacking_context_dirty = false;
  1378. stacking_context.clear();
  1379. }
  1380. // If our old z-index was not zero, then we must dirty our stacking context so we'll be re-indexed.
  1381. if (z_index != 0)
  1382. {
  1383. z_index = 0;
  1384. DirtyStackingContext();
  1385. }
  1386. }
  1387. else
  1388. {
  1389. float new_z_index = z_index_property.value;
  1390. if (new_z_index != z_index)
  1391. {
  1392. z_index = new_z_index;
  1393. if (parent != nullptr)
  1394. parent->DirtyStackingContext();
  1395. }
  1396. if (!local_stacking_context)
  1397. {
  1398. local_stacking_context = true;
  1399. stacking_context_dirty = true;
  1400. }
  1401. }
  1402. }
  1403. // Dirty the background if it's changed.
  1404. if (changed_properties.Contains(PropertyId::BackgroundColor) ||
  1405. changed_properties.Contains(PropertyId::Opacity) ||
  1406. changed_properties.Contains(PropertyId::ImageColor)) {
  1407. background->DirtyBackground();
  1408. }
  1409. // Dirty the decoration if it's changed.
  1410. if (changed_properties.Contains(PropertyId::Decorator) ||
  1411. changed_properties.Contains(PropertyId::Opacity) ||
  1412. changed_properties.Contains(PropertyId::ImageColor)) {
  1413. decoration->DirtyDecorators();
  1414. }
  1415. // Dirty the border if it's changed.
  1416. if (changed_properties.Contains(PropertyId::BorderTopWidth) ||
  1417. changed_properties.Contains(PropertyId::BorderRightWidth) ||
  1418. changed_properties.Contains(PropertyId::BorderBottomWidth) ||
  1419. changed_properties.Contains(PropertyId::BorderLeftWidth) ||
  1420. changed_properties.Contains(PropertyId::BorderTopColor) ||
  1421. changed_properties.Contains(PropertyId::BorderRightColor) ||
  1422. changed_properties.Contains(PropertyId::BorderBottomColor) ||
  1423. changed_properties.Contains(PropertyId::BorderLeftColor) ||
  1424. changed_properties.Contains(PropertyId::Opacity))
  1425. border->DirtyBorder();
  1426. // Check for clipping state changes
  1427. if (changed_properties.Contains(PropertyId::Clip) ||
  1428. changed_properties.Contains(PropertyId::OverflowX) ||
  1429. changed_properties.Contains(PropertyId::OverflowY))
  1430. {
  1431. clipping_state_dirty = true;
  1432. }
  1433. // Check for `perspective' and `perspective-origin' changes
  1434. if (changed_properties.Contains(PropertyId::Perspective) ||
  1435. changed_properties.Contains(PropertyId::PerspectiveOriginX) ||
  1436. changed_properties.Contains(PropertyId::PerspectiveOriginY))
  1437. {
  1438. DirtyTransformState(true, false);
  1439. }
  1440. // Check for `transform' and `transform-origin' changes
  1441. if (changed_properties.Contains(PropertyId::Transform) ||
  1442. changed_properties.Contains(PropertyId::TransformOriginX) ||
  1443. changed_properties.Contains(PropertyId::TransformOriginY) ||
  1444. changed_properties.Contains(PropertyId::TransformOriginZ))
  1445. {
  1446. DirtyTransformState(false, true);
  1447. }
  1448. // Check for `animation' changes
  1449. if (changed_properties.Contains(PropertyId::Animation))
  1450. {
  1451. dirty_animation = true;
  1452. }
  1453. // Check for `transition' changes
  1454. if (changed_properties.Contains(PropertyId::Transition))
  1455. {
  1456. dirty_transition = true;
  1457. }
  1458. }
  1459. // Called when a child node has been added somewhere in the hierarchy
  1460. void Element::OnChildAdd(Element* child)
  1461. {
  1462. }
  1463. // Called when a child node has been removed somewhere in the hierarchy
  1464. void Element::OnChildRemove(Element* child)
  1465. {
  1466. }
  1467. // Forces a re-layout of this element, and any other children required.
  1468. void Element::DirtyLayout()
  1469. {
  1470. Element* document = GetOwnerDocument();
  1471. if (document != nullptr)
  1472. document->DirtyLayout();
  1473. }
  1474. // Forces a re-layout of this element, and any other children required.
  1475. bool Element::IsLayoutDirty()
  1476. {
  1477. Element* document = GetOwnerDocument();
  1478. if (document != nullptr)
  1479. return document->IsLayoutDirty();
  1480. return false;
  1481. }
  1482. void Element::ProcessDefaultAction(Event& event)
  1483. {
  1484. if (event == EventId::Mousedown && IsPointWithinElement(Vector2f(event.GetParameter< float >("mouse_x", 0), event.GetParameter< float >("mouse_y", 0))) &&
  1485. event.GetParameter< int >("button", 0) == 0)
  1486. SetPseudoClass("active", true);
  1487. if (event == EventId::Mousescroll)
  1488. {
  1489. if (GetScrollHeight() > GetClientHeight())
  1490. {
  1491. Style::Overflow overflow_property = element_meta->computed_values.overflow_y;
  1492. if (overflow_property == Style::Overflow::Auto ||
  1493. overflow_property == Style::Overflow::Scroll)
  1494. {
  1495. // Stop the propagation if the current element has scrollbars.
  1496. // This prevents scrolling in parent elements, which is often unintended. If instead desired behavior is
  1497. // to scroll in parent elements when reaching top/bottom, move StopPropagation inside the next if statement.
  1498. event.StopPropagation();
  1499. const float wheel_delta = event.GetParameter< float >("wheel_delta", 0.f);
  1500. if ((wheel_delta < 0 && GetScrollTop() > 0) ||
  1501. (wheel_delta > 0 && GetScrollHeight() > GetScrollTop() + GetClientHeight()))
  1502. {
  1503. // Defined as three times the default line-height, multiplied by the dp ratio.
  1504. float default_scroll_length = 3.f * DefaultComputedValues.line_height.value;
  1505. if (const Context* context = GetContext())
  1506. default_scroll_length *= context->GetDensityIndependentPixelRatio();
  1507. SetScrollTop(GetScrollTop() + Math::RoundFloat(wheel_delta * default_scroll_length));
  1508. }
  1509. }
  1510. }
  1511. return;
  1512. }
  1513. if (event.GetPhase() == EventPhase::Target)
  1514. {
  1515. switch (event.GetId())
  1516. {
  1517. case EventId::Mouseover:
  1518. SetPseudoClass("hover", true);
  1519. break;
  1520. case EventId::Mouseout:
  1521. SetPseudoClass("hover", false);
  1522. break;
  1523. case EventId::Focus:
  1524. SetPseudoClass(FOCUS, true);
  1525. break;
  1526. case EventId::Blur:
  1527. SetPseudoClass(FOCUS, false);
  1528. break;
  1529. default:
  1530. break;
  1531. }
  1532. }
  1533. }
  1534. const Style::ComputedValues& Element::GetComputedValues() const
  1535. {
  1536. return element_meta->computed_values;
  1537. }
  1538. void Element::GetRML(String& content)
  1539. {
  1540. // First we start the open tag, add the attributes then close the open tag.
  1541. // Then comes the children in order, then we add our close tag.
  1542. content += "<";
  1543. content += tag;
  1544. for( auto& pair : attributes)
  1545. {
  1546. auto& name = pair.first;
  1547. auto& variant = pair.second;
  1548. String value;
  1549. if (variant.GetInto(value))
  1550. content += " " + name + "=\"" + value + "\"";
  1551. }
  1552. if (HasChildNodes())
  1553. {
  1554. content += ">";
  1555. GetInnerRML(content);
  1556. content += "</";
  1557. content += tag;
  1558. content += ">";
  1559. }
  1560. else
  1561. {
  1562. content += " />";
  1563. }
  1564. }
  1565. void Element::SetOwnerDocument(ElementDocument* document)
  1566. {
  1567. // If this element is a document, then never change owner_document.
  1568. if (owner_document != this)
  1569. {
  1570. if (owner_document && !document)
  1571. {
  1572. // We are detaching from the document and thereby also the context.
  1573. if (Context * context = owner_document->GetContext())
  1574. context->OnElementDetach(this);
  1575. }
  1576. if (owner_document != document)
  1577. {
  1578. owner_document = document;
  1579. for (ElementPtr& child : children)
  1580. child->SetOwnerDocument(document);
  1581. }
  1582. }
  1583. }
  1584. void Element::Release()
  1585. {
  1586. if (instancer)
  1587. instancer->ReleaseElement(this);
  1588. else
  1589. Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via RmlUi Factory. Unable to release.", GetAddress().c_str());
  1590. }
  1591. void Element::SetParent(Element* _parent)
  1592. {
  1593. // Assumes we are already detached from the hierarchy or we are detaching now.
  1594. RMLUI_ASSERT(!parent || !_parent);
  1595. parent = _parent;
  1596. if (parent)
  1597. {
  1598. // We need to update our definition and make sure we inherit the properties of our new parent.
  1599. style->DirtyDefinition();
  1600. style->DirtyInheritedProperties();
  1601. }
  1602. // The transform state may require recalculation.
  1603. if (transform_state || (parent && parent->transform_state))
  1604. DirtyTransformState(true, true);
  1605. SetOwnerDocument(parent ? parent->GetOwnerDocument() : nullptr);
  1606. }
  1607. void Element::DirtyOffset()
  1608. {
  1609. if(!offset_dirty)
  1610. {
  1611. offset_dirty = true;
  1612. if(transform_state)
  1613. DirtyTransformState(true, true);
  1614. // Not strictly true ... ?
  1615. for (size_t i = 0; i < children.size(); i++)
  1616. children[i]->DirtyOffset();
  1617. }
  1618. }
  1619. void Element::UpdateOffset()
  1620. {
  1621. using namespace Style;
  1622. const auto& computed = element_meta->computed_values;
  1623. Position position_property = computed.position;
  1624. if (position_property == Position::Absolute ||
  1625. position_property == Position::Fixed)
  1626. {
  1627. if (offset_parent != nullptr)
  1628. {
  1629. const Box& parent_box = offset_parent->GetBox();
  1630. Vector2f containing_block = parent_box.GetSize(Box::PADDING);
  1631. // If the element is anchored left, then the position is offset by that resolved value.
  1632. if (computed.left.type != Left::Auto)
  1633. relative_offset_base.x = parent_box.GetEdge(Box::BORDER, Box::LEFT) + (ResolveValue(computed.left, containing_block.x) + GetBox().GetEdge(Box::MARGIN, Box::LEFT));
  1634. // If the element is anchored right, then the position is set first so the element's right-most edge
  1635. // (including margins) will render up against the containing box's right-most content edge, and then
  1636. // offset by the resolved value.
  1637. else if (computed.right.type != Right::Auto)
  1638. relative_offset_base.x = containing_block.x + parent_box.GetEdge(Box::BORDER, Box::LEFT) - (ResolveValue(computed.right, containing_block.x) + GetBox().GetSize(Box::BORDER).x + GetBox().GetEdge(Box::MARGIN, Box::RIGHT));
  1639. // If the element is anchored top, then the position is offset by that resolved value.
  1640. if (computed.top.type != Top::Auto)
  1641. relative_offset_base.y = parent_box.GetEdge(Box::BORDER, Box::TOP) + (ResolveValue(computed.top, containing_block.y) + GetBox().GetEdge(Box::MARGIN, Box::TOP));
  1642. // If the element is anchored bottom, then the position is set first so the element's right-most edge
  1643. // (including margins) will render up against the containing box's right-most content edge, and then
  1644. // offset by the resolved value.
  1645. else if (computed.bottom.type != Bottom::Auto)
  1646. relative_offset_base.y = containing_block.y + parent_box.GetEdge(Box::BORDER, Box::TOP) - (ResolveValue(computed.bottom, containing_block.y) + GetBox().GetSize(Box::BORDER).y + GetBox().GetEdge(Box::MARGIN, Box::BOTTOM));
  1647. }
  1648. }
  1649. else if (position_property == Position::Relative)
  1650. {
  1651. if (offset_parent != nullptr)
  1652. {
  1653. const Box& parent_box = offset_parent->GetBox();
  1654. Vector2f containing_block = parent_box.GetSize();
  1655. if (computed.left.type != Left::Auto)
  1656. relative_offset_position.x = ResolveValue(computed.left, containing_block.x);
  1657. else if (computed.right.type != Right::Auto)
  1658. relative_offset_position.x = -1 * ResolveValue(computed.right, containing_block.x);
  1659. else
  1660. relative_offset_position.x = 0;
  1661. if (computed.top.type != Top::Auto)
  1662. relative_offset_position.y = ResolveValue(computed.top, containing_block.y);
  1663. else if (computed.bottom.type != Bottom::Auto)
  1664. relative_offset_position.y = -1 * ResolveValue(computed.bottom, containing_block.y);
  1665. else
  1666. relative_offset_position.y = 0;
  1667. }
  1668. }
  1669. else
  1670. {
  1671. relative_offset_position.x = 0;
  1672. relative_offset_position.y = 0;
  1673. }
  1674. }
  1675. void Element::BuildLocalStackingContext()
  1676. {
  1677. stacking_context_dirty = false;
  1678. stacking_context.clear();
  1679. BuildStackingContext(&stacking_context);
  1680. std::stable_sort(stacking_context.begin(), stacking_context.end(), ElementSortZIndex());
  1681. }
  1682. void Element::BuildStackingContext(ElementList* new_stacking_context)
  1683. {
  1684. RMLUI_ZoneScoped;
  1685. // Build the list of ordered children. Our child list is sorted within the stacking context so stacked elements
  1686. // will render in the right order; ie, positioned elements will render on top of inline elements, which will render
  1687. // on top of floated elements, which will render on top of block elements.
  1688. std::vector< std::pair< Element*, float > > ordered_children;
  1689. for (size_t i = 0; i < children.size(); ++i)
  1690. {
  1691. Element* child = children[i].get();
  1692. if (!child->IsVisible())
  1693. continue;
  1694. std::pair< Element*, float > ordered_child;
  1695. ordered_child.first = child;
  1696. if (child->GetPosition() != Style::Position::Static)
  1697. ordered_child.second = 3;
  1698. else if (child->GetFloat() != Style::Float::None)
  1699. ordered_child.second = 1;
  1700. else if (child->GetDisplay() == Style::Display::Block)
  1701. ordered_child.second = 0;
  1702. else
  1703. ordered_child.second = 2;
  1704. ordered_children.push_back(ordered_child);
  1705. }
  1706. // Sort the list!
  1707. std::stable_sort(ordered_children.begin(), ordered_children.end(), ElementSortZOrder());
  1708. // Add the list of ordered children into the stacking context in order.
  1709. for (size_t i = 0; i < ordered_children.size(); ++i)
  1710. {
  1711. new_stacking_context->push_back(ordered_children[i].first);
  1712. if (!ordered_children[i].first->local_stacking_context)
  1713. ordered_children[i].first->BuildStackingContext(new_stacking_context);
  1714. }
  1715. }
  1716. void Element::DirtyStackingContext()
  1717. {
  1718. // The first ancestor of ours that doesn't have an automatic z-index is the ancestor that is establishing our local
  1719. // stacking context.
  1720. Element* stacking_context_parent = this;
  1721. while (stacking_context_parent != nullptr &&
  1722. !stacking_context_parent->local_stacking_context)
  1723. stacking_context_parent = stacking_context_parent->GetParentNode();
  1724. if (stacking_context_parent != nullptr)
  1725. stacking_context_parent->stacking_context_dirty = true;
  1726. }
  1727. void Element::DirtyStructure()
  1728. {
  1729. structure_dirty = true;
  1730. }
  1731. void Element::UpdateStructure()
  1732. {
  1733. if (structure_dirty)
  1734. {
  1735. structure_dirty = false;
  1736. // If this element or its children depend on structured selectors, they may need to be updated.
  1737. GetStyle()->DirtyDefinition();
  1738. }
  1739. }
  1740. bool Element::Animate(const String & property_name, const Property & target_value, float duration, Tween tween, int num_iterations, bool alternate_direction, float delay, const Property* start_value)
  1741. {
  1742. bool result = false;
  1743. PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
  1744. auto it_animation = StartAnimation(property_id, start_value, num_iterations, alternate_direction, delay, false);
  1745. if (it_animation != animations.end())
  1746. {
  1747. result = it_animation->AddKey(duration, target_value, *this, tween, true);
  1748. if (!result)
  1749. animations.erase(it_animation);
  1750. }
  1751. return result;
  1752. }
  1753. bool Element::AddAnimationKey(const String & property_name, const Property & target_value, float duration, Tween tween)
  1754. {
  1755. ElementAnimation* animation = nullptr;
  1756. PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
  1757. for (auto& existing_animation : animations) {
  1758. if (existing_animation.GetPropertyId() == property_id) {
  1759. animation = &existing_animation;
  1760. break;
  1761. }
  1762. }
  1763. if (!animation)
  1764. return false;
  1765. bool result = animation->AddKey(animation->GetDuration() + duration, target_value, *this, tween, true);
  1766. return result;
  1767. }
  1768. ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, const Property* start_value, int num_iterations, bool alternate_direction, float delay, bool origin_is_animation_property)
  1769. {
  1770. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == property_id; });
  1771. if (it == animations.end())
  1772. {
  1773. animations.emplace_back();
  1774. it = animations.end() - 1;
  1775. }
  1776. Property value;
  1777. if (start_value)
  1778. {
  1779. value = *start_value;
  1780. if (!value.definition)
  1781. if(auto default_value = GetProperty(property_id))
  1782. value.definition = default_value->definition;
  1783. }
  1784. else if (auto default_value = GetProperty(property_id))
  1785. {
  1786. value = *default_value;
  1787. }
  1788. if (value.definition)
  1789. {
  1790. ElementAnimationOrigin origin = (origin_is_animation_property ? ElementAnimationOrigin::Animation : ElementAnimationOrigin::User);
  1791. double start_time = Clock::GetElapsedTime() + (double)delay;
  1792. *it = ElementAnimation{ property_id, origin, value, start_time, 0.0f, num_iterations, alternate_direction };
  1793. }
  1794. else
  1795. {
  1796. animations.erase(it);
  1797. it = animations.end();
  1798. }
  1799. return it;
  1800. }
  1801. bool Element::AddAnimationKeyTime(PropertyId property_id, const Property* target_value, float time, Tween tween)
  1802. {
  1803. if (!target_value)
  1804. target_value = style->GetProperty(property_id);
  1805. if (!target_value)
  1806. return false;
  1807. ElementAnimation* animation = nullptr;
  1808. for (auto& existing_animation : animations) {
  1809. if (existing_animation.GetPropertyId() == property_id) {
  1810. animation = &existing_animation;
  1811. break;
  1812. }
  1813. }
  1814. if (!animation)
  1815. return false;
  1816. bool result = animation->AddKey(time, *target_value, *this, tween, true);
  1817. return result;
  1818. }
  1819. bool Element::StartTransition(const Transition & transition, const Property& start_value, const Property & target_value)
  1820. {
  1821. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == transition.id; });
  1822. if (it != animations.end() && !it->IsTransition())
  1823. return false;
  1824. float duration = transition.duration;
  1825. double start_time = Clock::GetElapsedTime() + (double)transition.delay;
  1826. if (it == animations.end())
  1827. {
  1828. // Add transition as new animation
  1829. animations.push_back(
  1830. ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, start_time, 0.0f, 1, false }
  1831. );
  1832. it = (animations.end() - 1);
  1833. }
  1834. else
  1835. {
  1836. // Compress the duration based on the progress of the current animation
  1837. float f = it->GetInterpolationFactor();
  1838. f = 1.0f - (1.0f - f)*transition.reverse_adjustment_factor;
  1839. duration = duration * f;
  1840. // Replace old transition
  1841. *it = ElementAnimation{ transition.id, ElementAnimationOrigin::Transition, start_value, start_time, 0.0f, 1, false };
  1842. }
  1843. bool result = it->AddKey(duration, target_value, *this, transition.tween, true);
  1844. if (result)
  1845. SetProperty(transition.id, start_value);
  1846. else
  1847. animations.erase(it);
  1848. return result;
  1849. }
  1850. void Element::UpdateTransition()
  1851. {
  1852. if(dirty_transition)
  1853. {
  1854. dirty_transition = false;
  1855. // Remove all transitions that are no longer in our local list
  1856. const TransitionList& keep_transitions = GetComputedValues().transition;
  1857. if (keep_transitions.all)
  1858. return;
  1859. auto it_remove = animations.end();
  1860. if (keep_transitions.none)
  1861. {
  1862. // All transitions should be removed, but only touch the animations that originate from the 'transition' property.
  1863. // Move all animations to be erased in a valid state at the end of the list, and erase later.
  1864. it_remove = std::partition(animations.begin(), animations.end(),
  1865. [](const ElementAnimation& animation) -> bool { return !animation.IsTransition(); }
  1866. );
  1867. }
  1868. else
  1869. {
  1870. // Only remove the transitions that are not in our keep list.
  1871. const auto& keep_transitions_list = keep_transitions.transitions;
  1872. it_remove = std::partition(animations.begin(), animations.end(),
  1873. [&keep_transitions_list](const ElementAnimation& animation) -> bool {
  1874. if (!animation.IsTransition())
  1875. return true;
  1876. auto it = std::find_if(keep_transitions_list.begin(), keep_transitions_list.end(),
  1877. [&animation](const Transition& transition) { return animation.GetPropertyId() == transition.id; }
  1878. );
  1879. bool keep_animation = (it != keep_transitions_list.end());
  1880. return keep_animation;
  1881. }
  1882. );
  1883. }
  1884. // We can decide what to do with ended animations here, just removing them seems to be the CSS approach.
  1885. for (auto it = it_remove; it != animations.end(); ++it)
  1886. RemoveProperty(it->GetPropertyId());
  1887. animations.erase(it_remove, animations.end());
  1888. }
  1889. }
  1890. void Element::UpdateAnimation()
  1891. {
  1892. if (dirty_animation)
  1893. {
  1894. dirty_animation = false;
  1895. const AnimationList& animation_list = element_meta->computed_values.animation;
  1896. bool element_has_animations = (!animation_list.empty() || !animations.empty());
  1897. StyleSheet* stylesheet = nullptr;
  1898. if (element_has_animations && (stylesheet = GetStyleSheet().get()))
  1899. {
  1900. // Remove existing animations
  1901. // Note: We are effectively restarting all animations whenever 'drty_animation' is set. Use the dirty flag with care,
  1902. // or find another approach which only updates actual "dirty" animations.
  1903. {
  1904. // We only touch the animations that originate from the 'animation' property.
  1905. auto it_remove = std::partition(animations.begin(), animations.end(),
  1906. [](const ElementAnimation & animation) { return animation.GetOrigin() != ElementAnimationOrigin::Animation; }
  1907. );
  1908. // We can decide what to do with ended animations here, should be consistent with removal of transitions.
  1909. for (auto it = it_remove; it != animations.end(); ++it)
  1910. RemoveProperty(it->GetPropertyId());
  1911. animations.erase(it_remove, animations.end());
  1912. }
  1913. // Start animations
  1914. for (const auto& animation : animation_list)
  1915. {
  1916. const Keyframes* keyframes_ptr = stylesheet->GetKeyframes(animation.name);
  1917. if (keyframes_ptr && keyframes_ptr->blocks.size() >= 1 && !animation.paused)
  1918. {
  1919. auto& property_ids = keyframes_ptr->property_ids;
  1920. auto& blocks = keyframes_ptr->blocks;
  1921. bool has_from_key = (blocks[0].normalized_time == 0);
  1922. bool has_to_key = (blocks.back().normalized_time == 1);
  1923. // If the first key defines initial conditions for a given property, use those values, else, use this element's current values.
  1924. for (PropertyId id : property_ids)
  1925. StartAnimation(id, (has_from_key ? blocks[0].properties.GetProperty(id) : nullptr), animation.num_iterations, animation.alternate, animation.delay, true);
  1926. // Need to skip the first and last keys if they set the initial and end conditions, respectively.
  1927. for (int i = (has_from_key ? 1 : 0); i < (int)blocks.size() + (has_to_key ? -1 : 0); i++)
  1928. {
  1929. // Add properties of current key to animation
  1930. float time = blocks[i].normalized_time * animation.duration;
  1931. for (auto& property : blocks[i].properties.GetProperties())
  1932. AddAnimationKeyTime(property.first, &property.second, time, animation.tween);
  1933. }
  1934. // If the last key defines end conditions for a given property, use those values, else, use this element's current values.
  1935. float time = animation.duration;
  1936. for (PropertyId id : property_ids)
  1937. AddAnimationKeyTime(id, (has_to_key ? blocks.back().properties.GetProperty(id) : nullptr), time, animation.tween);
  1938. }
  1939. }
  1940. }
  1941. }
  1942. }
  1943. void Element::AdvanceAnimations()
  1944. {
  1945. if (!animations.empty())
  1946. {
  1947. double time = Clock::GetElapsedTime();
  1948. for (auto& animation : animations)
  1949. {
  1950. Property property = animation.UpdateAndGetProperty(time, *this);
  1951. if (property.unit != Property::UNKNOWN)
  1952. SetProperty(animation.GetPropertyId(), property);
  1953. }
  1954. // Move all completed animations to the end of the list
  1955. auto it_completed = std::partition(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return !animation.IsComplete(); });
  1956. std::vector<Dictionary> dictionary_list;
  1957. std::vector<bool> is_transition;
  1958. dictionary_list.reserve(animations.end() - it_completed);
  1959. is_transition.reserve(animations.end() - it_completed);
  1960. for (auto it = it_completed; it != animations.end(); ++it)
  1961. {
  1962. dictionary_list.emplace_back();
  1963. dictionary_list.back().emplace("property", StyleSheetSpecification::GetPropertyName(it->GetPropertyId()));
  1964. is_transition.push_back(it->IsTransition());
  1965. }
  1966. // Need to erase elements before submitting event, as iterators might be invalidated when calling external code.
  1967. animations.erase(it_completed, animations.end());
  1968. for (size_t i = 0; i < dictionary_list.size(); i++)
  1969. DispatchEvent(is_transition[i] ? EventId::Transitionend : EventId::Animationend, dictionary_list[i]);
  1970. }
  1971. }
  1972. void Element::DirtyTransformState(bool perspective_dirty, bool transform_dirty)
  1973. {
  1974. dirty_perspective |= perspective_dirty;
  1975. dirty_transform |= transform_dirty;
  1976. }
  1977. void Element::UpdateTransformState()
  1978. {
  1979. if (!dirty_perspective && !dirty_transform)
  1980. return;
  1981. const ComputedValues& computed = element_meta->computed_values;
  1982. const Vector2f pos = GetAbsoluteOffset(Box::BORDER);
  1983. const Vector2f size = GetBox().GetSize(Box::BORDER);
  1984. bool perspective_or_transform_changed = false;
  1985. if (dirty_perspective)
  1986. {
  1987. // If perspective is set on this element, then it applies to our children. We just calculate it here,
  1988. // and let the children's transform update merge it with their transform.
  1989. bool had_perspective = (transform_state && transform_state->GetLocalPerspective());
  1990. float distance = computed.perspective;
  1991. Vector2f vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
  1992. bool have_perspective = false;
  1993. if (distance > 0.0f)
  1994. {
  1995. have_perspective = true;
  1996. // Compute the vanishing point from the perspective origin
  1997. if (computed.perspective_origin_x.type == Style::PerspectiveOrigin::Percentage)
  1998. vanish.x = pos.x + computed.perspective_origin_x.value * 0.01f * size.x;
  1999. else
  2000. vanish.x = pos.x + computed.perspective_origin_x.value;
  2001. if (computed.perspective_origin_y.type == Style::PerspectiveOrigin::Percentage)
  2002. vanish.y = pos.y + computed.perspective_origin_y.value * 0.01f * size.y;
  2003. else
  2004. vanish.y = pos.y + computed.perspective_origin_y.value;
  2005. }
  2006. if (have_perspective)
  2007. {
  2008. // Equivalent to: Translate(x,y,0) * Perspective(distance) * Translate(-x,-y,0)
  2009. Matrix4f perspective = Matrix4f::FromRows(
  2010. { 1, 0, -vanish.x / distance, 0 },
  2011. { 0, 1, -vanish.y / distance, 0 },
  2012. { 0, 0, 1, 0 },
  2013. { 0, 0, -1 / distance, 1 }
  2014. );
  2015. if (!transform_state)
  2016. transform_state = std::make_unique<TransformState>();
  2017. perspective_or_transform_changed |= transform_state->SetLocalPerspective(&perspective);
  2018. }
  2019. else if (transform_state)
  2020. transform_state->SetLocalPerspective(nullptr);
  2021. perspective_or_transform_changed |= (have_perspective != had_perspective);
  2022. dirty_perspective = false;
  2023. }
  2024. if (dirty_transform)
  2025. {
  2026. // We want to find the accumulated transform given all our ancestors. It is assumed here that the parent transform is already updated,
  2027. // so that we only need to consider our local transform and combine it with our parent's transform and perspective matrices.
  2028. bool had_transform = (transform_state && transform_state->GetTransform());
  2029. bool have_transform = false;
  2030. Matrix4f transform = Matrix4f::Identity();
  2031. if (computed.transform)
  2032. {
  2033. // First find the current element's transform
  2034. const int n = computed.transform->GetNumPrimitives();
  2035. for (int i = 0; i < n; ++i)
  2036. {
  2037. const Transforms::Primitive& primitive = computed.transform->GetPrimitive(i);
  2038. Matrix4f matrix;
  2039. if (primitive.ResolveTransform(matrix, *this))
  2040. {
  2041. transform *= matrix;
  2042. have_transform = true;
  2043. }
  2044. }
  2045. if(have_transform)
  2046. {
  2047. // Compute the transform origin
  2048. Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
  2049. if (computed.transform_origin_x.type == Style::TransformOrigin::Percentage)
  2050. transform_origin.x = pos.x + computed.transform_origin_x.value * size.x * 0.01f;
  2051. else
  2052. transform_origin.x = pos.x + computed.transform_origin_x.value;
  2053. if (computed.transform_origin_y.type == Style::TransformOrigin::Percentage)
  2054. transform_origin.y = pos.y + computed.transform_origin_y.value * size.y * 0.01f;
  2055. else
  2056. transform_origin.y = pos.y + computed.transform_origin_y.value;
  2057. transform_origin.z = computed.transform_origin_z;
  2058. // Make the transformation apply relative to the transform origin
  2059. transform = Matrix4f::Translate(transform_origin) * transform * Matrix4f::Translate(-transform_origin);
  2060. }
  2061. // We may want to include the local offsets here, as suggested by the CSS specs, so that the local transform is applied after the offset I believe
  2062. // the motivation is. Then we would need to subtract the absolute zero-offsets during geometry submit whenever we have transforms.
  2063. }
  2064. if (parent && parent->transform_state)
  2065. {
  2066. // Apply the parent's local perspective and transform.
  2067. // @performance: If we have no local transform and no parent perspective, we can effectively just point to the parent transform instead of copying it.
  2068. const TransformState& parent_state = *parent->transform_state;
  2069. if (auto parent_perspective = parent_state.GetLocalPerspective())
  2070. {
  2071. transform = *parent_perspective * transform;
  2072. have_transform = true;
  2073. }
  2074. if (auto parent_transform = parent_state.GetTransform())
  2075. {
  2076. transform = *parent_transform * transform;
  2077. have_transform = true;
  2078. }
  2079. }
  2080. if (have_transform)
  2081. {
  2082. if (!transform_state)
  2083. transform_state = std::make_unique<TransformState>();
  2084. perspective_or_transform_changed |= transform_state->SetTransform(&transform);
  2085. }
  2086. else if (transform_state)
  2087. transform_state->SetTransform(nullptr);
  2088. perspective_or_transform_changed |= (had_transform != have_transform);
  2089. }
  2090. // A change in perspective or transform will require an update to children transforms as well.
  2091. if (perspective_or_transform_changed)
  2092. {
  2093. for (size_t i = 0; i < children.size(); i++)
  2094. children[i]->DirtyTransformState(false, true);
  2095. }
  2096. // No reason to keep the transform state around if transform and perspective have been removed.
  2097. if (transform_state && !transform_state->GetTransform() && !transform_state->GetLocalPerspective())
  2098. {
  2099. transform_state.reset();
  2100. }
  2101. }
  2102. }
  2103. }