Element.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../../Include/RmlUi/Core/Element.h"
  29. #include "../../Include/RmlUi/Core/Context.h"
  30. #include "../../Include/RmlUi/Core/Core.h"
  31. #include "../../Include/RmlUi/Core/Dictionary.h"
  32. #include "../../Include/RmlUi/Core/ElementDocument.h"
  33. #include "../../Include/RmlUi/Core/ElementInstancer.h"
  34. #include "../../Include/RmlUi/Core/ElementScroll.h"
  35. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  36. #include "../../Include/RmlUi/Core/Factory.h"
  37. #include "../../Include/RmlUi/Core/Profiling.h"
  38. #include "../../Include/RmlUi/Core/PropertiesIteratorView.h"
  39. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  40. #include "../../Include/RmlUi/Core/PropertyIdSet.h"
  41. #include "../../Include/RmlUi/Core/StyleSheet.h"
  42. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  43. #include "../../Include/RmlUi/Core/TransformPrimitive.h"
  44. #include "Clock.h"
  45. #include "ComputeProperty.h"
  46. #include "DataModel.h"
  47. #include "ElementAnimation.h"
  48. #include "ElementBackgroundBorder.h"
  49. #include "ElementDefinition.h"
  50. #include "ElementEffects.h"
  51. #include "ElementMeta.h"
  52. #include "ElementStyle.h"
  53. #include "EventDispatcher.h"
  54. #include "EventSpecification.h"
  55. #include "Layout/LayoutEngine.h"
  56. #include "PluginRegistry.h"
  57. #include "Pool.h"
  58. #include "PropertiesIterator.h"
  59. #include "StyleSheetNode.h"
  60. #include "StyleSheetParser.h"
  61. #include "TransformState.h"
  62. #include "TransformUtilities.h"
  63. #include "XMLParseTools.h"
  64. #include <algorithm>
  65. #include <cmath>
  66. namespace Rml {
  67. // Determines how many levels up in the hierarchy the OnChildAdd and OnChildRemove are called (starting at the child itself)
  68. static constexpr int ChildNotifyLevels = 2;
  69. // Helper function to select scroll offset delta
  70. static float GetScrollOffsetDelta(ScrollAlignment alignment, float begin_offset, float end_offset)
  71. {
  72. switch (alignment)
  73. {
  74. case ScrollAlignment::Start: return begin_offset;
  75. case ScrollAlignment::Center: return (begin_offset + end_offset) / 2.0f;
  76. case ScrollAlignment::End: return end_offset;
  77. case ScrollAlignment::Nearest:
  78. if (begin_offset >= 0.f && end_offset <= 0.f)
  79. return 0.f; // Element is already visible, don't scroll
  80. else if (begin_offset < 0.f && end_offset < 0.f)
  81. return Math::Max(begin_offset, end_offset);
  82. else if (begin_offset > 0.f && end_offset > 0.f)
  83. return Math::Min(begin_offset, end_offset);
  84. else
  85. return 0.f; // Shouldn't happen
  86. }
  87. return 0.f;
  88. }
  89. Element::Element(const String& tag) :
  90. local_stacking_context(false), local_stacking_context_forced(false), stacking_context_dirty(false), computed_values_are_default_initialized(true),
  91. visible(true), offset_fixed(false), absolute_offset_dirty(true), rounded_main_padding_size_dirty(true), dirty_definition(false),
  92. dirty_child_definitions(false), dirty_animation(false), dirty_transition(false), dirty_transform(false), dirty_perspective(false), tag(tag),
  93. relative_offset_base(0, 0), relative_offset_position(0, 0), absolute_offset(0, 0), scroll_offset(0, 0)
  94. {
  95. RMLUI_ASSERT(tag == StringUtilities::ToLower(tag));
  96. parent = nullptr;
  97. focus = nullptr;
  98. instancer = nullptr;
  99. owner_document = nullptr;
  100. offset_parent = nullptr;
  101. clip_area = BoxArea::Padding;
  102. baseline = 0.0f;
  103. num_non_dom_children = 0;
  104. z_index = 0;
  105. meta = ElementMetaPool::element_meta_pool->pool.AllocateAndConstruct(this);
  106. data_model = nullptr;
  107. }
  108. Element::~Element()
  109. {
  110. RMLUI_ASSERT(parent == nullptr);
  111. PluginRegistry::NotifyElementDestroy(this);
  112. // A simplified version of RemoveChild() for destruction.
  113. for (ElementPtr& child : children)
  114. {
  115. Element* child_ancestor = child.get();
  116. for (int i = 0; i <= ChildNotifyLevels && child_ancestor; i++, child_ancestor = child_ancestor->GetParentNode())
  117. child_ancestor->OnChildRemove(child.get());
  118. child->SetParent(nullptr);
  119. }
  120. children.clear();
  121. num_non_dom_children = 0;
  122. ElementMetaPool::element_meta_pool->pool.DestroyAndDeallocate(meta);
  123. }
  124. void Element::Update(float dp_ratio, Vector2f vp_dimensions)
  125. {
  126. #ifdef RMLUI_TRACY_PROFILING
  127. auto name = GetAddress(false, false);
  128. RMLUI_ZoneScoped;
  129. RMLUI_ZoneText(name.c_str(), name.size());
  130. #endif
  131. OnUpdate();
  132. HandleTransitionProperty();
  133. HandleAnimationProperty();
  134. AdvanceAnimations();
  135. meta->scroll.Update();
  136. UpdateProperties(dp_ratio, vp_dimensions);
  137. // Do en extra pass over the animations and properties if the 'animation' property was just changed.
  138. if (dirty_animation)
  139. {
  140. HandleAnimationProperty();
  141. AdvanceAnimations();
  142. UpdateProperties(dp_ratio, vp_dimensions);
  143. }
  144. meta->effects.InstanceEffects();
  145. for (size_t i = 0; i < children.size(); i++)
  146. children[i]->Update(dp_ratio, vp_dimensions);
  147. if (!animations.empty() && IsVisible(true))
  148. {
  149. if (Context* ctx = GetContext())
  150. ctx->RequestNextUpdate(0);
  151. }
  152. }
  153. void Element::UpdateProperties(const float dp_ratio, const Vector2f vp_dimensions)
  154. {
  155. UpdateDefinition();
  156. if (meta->style.AnyPropertiesDirty())
  157. {
  158. const ComputedValues* parent_values = parent ? &parent->GetComputedValues() : nullptr;
  159. const ComputedValues* document_values = owner_document ? &owner_document->GetComputedValues() : nullptr;
  160. // Compute values and clear dirty properties
  161. PropertyIdSet dirty_properties = meta->style.ComputeValues(meta->computed_values, parent_values, document_values,
  162. computed_values_are_default_initialized, dp_ratio, vp_dimensions);
  163. computed_values_are_default_initialized = false;
  164. // Computed values are just calculated and can safely be used in OnPropertyChange.
  165. // However, new properties set during this call will not be available until the next update loop.
  166. if (!dirty_properties.Empty())
  167. OnPropertyChange(dirty_properties);
  168. }
  169. }
  170. void Element::Render()
  171. {
  172. #ifdef RMLUI_TRACY_PROFILING
  173. auto name = GetAddress(false, false);
  174. RMLUI_ZoneScoped;
  175. RMLUI_ZoneText(name.c_str(), name.size());
  176. #endif
  177. UpdateAbsoluteOffsetAndRenderBoxData();
  178. // Rebuild our stacking context if necessary.
  179. if (stacking_context_dirty)
  180. BuildLocalStackingContext();
  181. UpdateTransformState();
  182. // Apply our transform
  183. ElementUtilities::ApplyTransform(*this);
  184. meta->effects.RenderEffects(RenderStage::Enter);
  185. // Set up the clipping region for this element.
  186. if (ElementUtilities::SetClippingRegion(this))
  187. {
  188. meta->background_border.Render(this);
  189. meta->effects.RenderEffects(RenderStage::Decoration);
  190. {
  191. RMLUI_ZoneScopedNC("OnRender", 0x228B22);
  192. OnRender();
  193. }
  194. }
  195. // Render all elements in our local stacking context.
  196. for (Element* element : stacking_context)
  197. element->Render();
  198. meta->effects.RenderEffects(RenderStage::Exit);
  199. }
  200. ElementPtr Element::Clone() const
  201. {
  202. ElementPtr clone;
  203. if (instancer)
  204. {
  205. clone = instancer->InstanceElement(nullptr, GetTagName(), attributes);
  206. if (clone)
  207. clone->SetInstancer(instancer);
  208. }
  209. else
  210. clone = Factory::InstanceElement(nullptr, GetTagName(), GetTagName(), attributes);
  211. if (clone)
  212. {
  213. // Copy over the attributes. The 'style' and 'class' attributes are skipped because inline styles and class names are copied manually below.
  214. // This is necessary in case any properties or classes have been set manually, in which case the 'style' and 'class' attributes are out of
  215. // sync with the used style and active classes.
  216. ElementAttributes clone_attributes = attributes;
  217. clone_attributes.erase("style");
  218. clone_attributes.erase("class");
  219. clone->SetAttributes(clone_attributes);
  220. for (auto& id_property : GetStyle()->GetLocalStyleProperties())
  221. clone->SetProperty(id_property.first, id_property.second);
  222. clone->GetStyle()->SetClassNames(GetStyle()->GetClassNames());
  223. String inner_rml;
  224. GetInnerRML(inner_rml);
  225. clone->SetInnerRML(inner_rml);
  226. }
  227. return clone;
  228. }
  229. void Element::SetClass(const String& class_name, bool activate)
  230. {
  231. if (meta->style.SetClass(class_name, activate))
  232. DirtyDefinition(DirtyNodes::SelfAndSiblings);
  233. }
  234. bool Element::IsClassSet(const String& class_name) const
  235. {
  236. return meta->style.IsClassSet(class_name);
  237. }
  238. void Element::SetClassNames(const String& class_names)
  239. {
  240. SetAttribute("class", class_names);
  241. }
  242. String Element::GetClassNames() const
  243. {
  244. return meta->style.GetClassNames();
  245. }
  246. const StyleSheet* Element::GetStyleSheet() const
  247. {
  248. if (ElementDocument* document = GetOwnerDocument())
  249. return document->GetStyleSheet();
  250. return nullptr;
  251. }
  252. String Element::GetAddress(bool include_pseudo_classes, bool include_parents) const
  253. {
  254. // Add the tag name onto the address.
  255. String address(tag);
  256. // Add the ID if we have one.
  257. if (!id.empty())
  258. {
  259. address += "#";
  260. address += id;
  261. }
  262. String classes = meta->style.GetClassNames();
  263. if (!classes.empty())
  264. {
  265. classes = StringUtilities::Replace(classes, ' ', '.');
  266. address += ".";
  267. address += classes;
  268. }
  269. if (include_pseudo_classes)
  270. {
  271. const PseudoClassMap& pseudo_classes = meta->style.GetActivePseudoClasses();
  272. for (auto& pseudo_class : pseudo_classes)
  273. {
  274. address += ":";
  275. address += pseudo_class.first;
  276. }
  277. }
  278. if (include_parents && parent)
  279. {
  280. address += " < ";
  281. return address + parent->GetAddress(include_pseudo_classes, true);
  282. }
  283. else
  284. return address;
  285. }
  286. void Element::SetOffset(Vector2f offset, Element* _offset_parent, bool _offset_fixed)
  287. {
  288. _offset_fixed |= GetPosition() == Style::Position::Fixed;
  289. // If our offset has definitely changed, or any of our parenting has, then these are set and
  290. // updated based on our left / right / top / bottom properties.
  291. if (relative_offset_base != offset || offset_parent != _offset_parent || offset_fixed != _offset_fixed)
  292. {
  293. relative_offset_base = offset;
  294. offset_fixed = _offset_fixed;
  295. offset_parent = _offset_parent;
  296. UpdateOffset();
  297. DirtyAbsoluteOffset();
  298. }
  299. // Otherwise, our offset is updated in case left / right / top / bottom will have an impact on
  300. // our final position, and our children are dirtied if they do.
  301. else
  302. {
  303. const Vector2f old_base = relative_offset_base;
  304. const Vector2f old_position = relative_offset_position;
  305. UpdateOffset();
  306. if (old_base != relative_offset_base || old_position != relative_offset_position)
  307. DirtyAbsoluteOffset();
  308. }
  309. }
  310. Vector2f Element::GetRelativeOffset(BoxArea area)
  311. {
  312. return relative_offset_base + relative_offset_position + GetBox().GetPosition(area);
  313. }
  314. Vector2f Element::GetAbsoluteOffset(BoxArea area)
  315. {
  316. UpdateAbsoluteOffsetAndRenderBoxData();
  317. return area == BoxArea::Border ? absolute_offset : absolute_offset + GetBox().GetPosition(area);
  318. }
  319. void Element::UpdateAbsoluteOffsetAndRenderBoxData()
  320. {
  321. if (absolute_offset_dirty || rounded_main_padding_size_dirty)
  322. {
  323. absolute_offset_dirty = false;
  324. rounded_main_padding_size_dirty = false;
  325. Vector2f offset_from_ancestors;
  326. if (offset_parent)
  327. offset_from_ancestors = offset_parent->GetAbsoluteOffset(BoxArea::Border);
  328. if (!offset_fixed)
  329. {
  330. // Add any parent scrolling onto our position as well.
  331. if (offset_parent)
  332. offset_from_ancestors -= offset_parent->scroll_offset;
  333. // Finally, there may be relatively positioned elements between ourself and our containing block, add their relative offsets as well.
  334. for (Element* ancestor = parent; ancestor && ancestor != offset_parent; ancestor = ancestor->parent)
  335. offset_from_ancestors += ancestor->relative_offset_position;
  336. }
  337. const Vector2f relative_offset = relative_offset_base + relative_offset_position;
  338. absolute_offset = relative_offset + offset_from_ancestors;
  339. // Next, we find the rounded size of the box so that elements can be placed border-to-border next to each other
  340. // without any gaps. To achieve this, we have to adjust their rounded/rendered sizes based on their position, in
  341. // such a way that the bottom-right of this element exactly matches the top-left of the next element. The order
  342. // of floating-point operations matter here, we want to replicate the operations in the layout engine as close
  343. // as possible to avoid any gaps.
  344. const Vector2f main_padding_size = main_box.GetSize(BoxArea::Padding);
  345. const Vector2f bottom_right_absolute_offset = (relative_offset + main_padding_size) + offset_from_ancestors;
  346. const Vector2f new_rounded_main_padding_size = bottom_right_absolute_offset.Round() - absolute_offset.Round();
  347. if (new_rounded_main_padding_size != rounded_main_padding_size)
  348. {
  349. rounded_main_padding_size = new_rounded_main_padding_size;
  350. meta->background_border.DirtyBackground();
  351. meta->background_border.DirtyBorder();
  352. meta->effects.DirtyEffectsData();
  353. }
  354. }
  355. }
  356. void Element::SetClipArea(BoxArea _clip_area)
  357. {
  358. clip_area = _clip_area;
  359. }
  360. BoxArea Element::GetClipArea() const
  361. {
  362. return clip_area;
  363. }
  364. void Element::SetScrollableOverflowRectangle(Vector2f _scrollable_overflow_rectangle, bool clamp_scroll_offset)
  365. {
  366. if (scrollable_overflow_rectangle != _scrollable_overflow_rectangle)
  367. {
  368. scrollable_overflow_rectangle = _scrollable_overflow_rectangle;
  369. if (clamp_scroll_offset)
  370. ClampScrollOffset();
  371. }
  372. }
  373. void Element::SetBox(const Box& box)
  374. {
  375. if (box != main_box || additional_boxes.size() > 0)
  376. {
  377. #ifdef RMLUI_DEBUG
  378. for (const BoxEdge edge : {BoxEdge::Top, BoxEdge::Right, BoxEdge::Bottom, BoxEdge::Left})
  379. {
  380. const float border_width = box.GetEdge(BoxArea::Border, edge);
  381. if (border_width != Math::Round(border_width))
  382. Log::Message(Log::LT_WARNING, "Expected integer border width but got %g px on element: %s", border_width, GetAddress().c_str());
  383. }
  384. #endif
  385. main_box = box;
  386. additional_boxes.clear();
  387. OnResize();
  388. rounded_main_padding_size_dirty = true;
  389. meta->background_border.DirtyBackground();
  390. meta->background_border.DirtyBorder();
  391. meta->effects.DirtyEffectsData();
  392. }
  393. }
  394. void Element::AddBox(const Box& box, Vector2f offset)
  395. {
  396. additional_boxes.emplace_back(PositionedBox{box, offset});
  397. OnResize();
  398. meta->background_border.DirtyBackground();
  399. meta->background_border.DirtyBorder();
  400. meta->effects.DirtyEffectsData();
  401. }
  402. const Box& Element::GetBox()
  403. {
  404. return main_box;
  405. }
  406. const Box& Element::GetBox(int index, Vector2f& offset)
  407. {
  408. offset = Vector2f(0);
  409. const int additional_box_index = index - 1;
  410. if (index < 1 || additional_box_index >= (int)additional_boxes.size())
  411. return main_box;
  412. offset = additional_boxes[additional_box_index].offset;
  413. return additional_boxes[additional_box_index].box;
  414. }
  415. RenderBox Element::GetRenderBox(BoxArea fill_area, int index)
  416. {
  417. RMLUI_ASSERTMSG(fill_area >= BoxArea::Border && fill_area <= BoxArea::Content,
  418. "Render box can only be generated with fill area of border, padding or content.");
  419. UpdateAbsoluteOffsetAndRenderBoxData();
  420. struct BoxReference {
  421. const Box& box;
  422. Vector2f padding_size;
  423. Vector2f offset;
  424. };
  425. auto GetBoxAndOffset = [this, index]() {
  426. const int additional_box_index = index - 1;
  427. if (index < 1 || additional_box_index >= (int)additional_boxes.size())
  428. return BoxReference{main_box, rounded_main_padding_size, {}};
  429. const PositionedBox& positioned_box = additional_boxes[additional_box_index];
  430. return BoxReference{positioned_box.box, positioned_box.box.GetSize(BoxArea::Padding), positioned_box.offset.Round()};
  431. };
  432. BoxReference box = GetBoxAndOffset();
  433. EdgeSizes edge_sizes = {};
  434. for (int area = (int)BoxArea::Border; area < (int)fill_area; area++)
  435. {
  436. edge_sizes[0] += box.box.GetEdge(BoxArea(area), BoxEdge::Top);
  437. edge_sizes[1] += box.box.GetEdge(BoxArea(area), BoxEdge::Right);
  438. edge_sizes[2] += box.box.GetEdge(BoxArea(area), BoxEdge::Bottom);
  439. edge_sizes[3] += box.box.GetEdge(BoxArea(area), BoxEdge::Left);
  440. }
  441. Vector2f inner_size;
  442. switch (fill_area)
  443. {
  444. case BoxArea::Border: inner_size = box.padding_size + box.box.GetFrameSize(BoxArea::Border); break;
  445. case BoxArea::Padding: inner_size = box.padding_size; break;
  446. case BoxArea::Content: inner_size = box.padding_size - box.box.GetFrameSize(BoxArea::Padding); break;
  447. case BoxArea::Margin:
  448. case BoxArea::Auto: RMLUI_ERROR;
  449. }
  450. return RenderBox{inner_size, box.offset, edge_sizes, meta->computed_values.border_radius()};
  451. }
  452. int Element::GetNumBoxes()
  453. {
  454. return 1 + (int)additional_boxes.size();
  455. }
  456. float Element::GetBaseline() const
  457. {
  458. return baseline;
  459. }
  460. bool Element::GetIntrinsicDimensions(Vector2f& /*dimensions*/, float& /*ratio*/)
  461. {
  462. return false;
  463. }
  464. bool Element::IsReplaced()
  465. {
  466. Vector2f unused_dimensions;
  467. float unused_ratio = 0.f;
  468. return GetIntrinsicDimensions(unused_dimensions, unused_ratio);
  469. }
  470. bool Element::IsPointWithinElement(const Vector2f point)
  471. {
  472. const Vector2f position = GetAbsoluteOffset(BoxArea::Border);
  473. for (int i = 0; i < GetNumBoxes(); ++i)
  474. {
  475. Vector2f box_offset;
  476. const Box& box = GetBox(i, box_offset);
  477. const Vector2f box_position = position + box_offset;
  478. const Vector2f box_dimensions = box.GetSize(BoxArea::Border);
  479. if (point.x >= box_position.x && point.x <= (box_position.x + box_dimensions.x) && point.y >= box_position.y &&
  480. point.y <= (box_position.y + box_dimensions.y))
  481. {
  482. return true;
  483. }
  484. }
  485. return false;
  486. }
  487. bool Element::IsVisible(bool include_ancestors) const
  488. {
  489. if (!include_ancestors)
  490. return visible;
  491. const Element* element = this;
  492. while (element)
  493. {
  494. if (!element->visible)
  495. return false;
  496. element = element->parent;
  497. }
  498. return true;
  499. }
  500. float Element::GetZIndex() const
  501. {
  502. return z_index;
  503. }
  504. FontFaceHandle Element::GetFontFaceHandle() const
  505. {
  506. return meta->computed_values.font_face_handle();
  507. }
  508. bool Element::SetProperty(const String& name, const String& value)
  509. {
  510. // The name may be a shorthand giving us multiple underlying properties
  511. PropertyDictionary properties;
  512. if (!StyleSheetSpecification::ParsePropertyDeclaration(properties, name, value))
  513. {
  514. Log::Message(Log::LT_WARNING, "Syntax error parsing inline property declaration '%s: %s;'.", name.c_str(), value.c_str());
  515. return false;
  516. }
  517. for (auto& property : properties.GetProperties())
  518. {
  519. if (!meta->style.SetProperty(property.first, property.second))
  520. return false;
  521. }
  522. return true;
  523. }
  524. bool Element::SetProperty(PropertyId id, const Property& property)
  525. {
  526. return meta->style.SetProperty(id, property);
  527. }
  528. void Element::RemoveProperty(const String& name)
  529. {
  530. auto property_id = StyleSheetSpecification::GetPropertyId(name);
  531. if (property_id != PropertyId::Invalid)
  532. meta->style.RemoveProperty(property_id);
  533. else
  534. {
  535. auto shorthand_id = StyleSheetSpecification::GetShorthandId(name);
  536. if (shorthand_id != ShorthandId::Invalid)
  537. {
  538. auto property_id_set = StyleSheetSpecification::GetShorthandUnderlyingProperties(shorthand_id);
  539. for (auto it = property_id_set.begin(); it != property_id_set.end(); ++it)
  540. meta->style.RemoveProperty(*it);
  541. }
  542. }
  543. }
  544. void Element::RemoveProperty(PropertyId id)
  545. {
  546. meta->style.RemoveProperty(id);
  547. }
  548. const Property* Element::GetProperty(const String& name)
  549. {
  550. return meta->style.GetProperty(StyleSheetSpecification::GetPropertyId(name));
  551. }
  552. const Property* Element::GetProperty(PropertyId id)
  553. {
  554. return meta->style.GetProperty(id);
  555. }
  556. const Property* Element::GetLocalProperty(const String& name)
  557. {
  558. return meta->style.GetLocalProperty(StyleSheetSpecification::GetPropertyId(name));
  559. }
  560. const Property* Element::GetLocalProperty(PropertyId id)
  561. {
  562. return meta->style.GetLocalProperty(id);
  563. }
  564. const PropertyMap& Element::GetLocalStyleProperties()
  565. {
  566. return meta->style.GetLocalStyleProperties();
  567. }
  568. float Element::ResolveLength(NumericValue value)
  569. {
  570. float result = 0.f;
  571. if (Any(value.unit & Unit::LENGTH))
  572. result = meta->style.ResolveNumericValue(value, 0.f);
  573. return result;
  574. }
  575. float Element::ResolveNumericValue(NumericValue value, float base_value)
  576. {
  577. float result = 0.f;
  578. if (Any(value.unit & Unit::NUMERIC))
  579. result = meta->style.ResolveNumericValue(value, base_value);
  580. return result;
  581. }
  582. Vector2f Element::GetContainingBlock()
  583. {
  584. Vector2f containing_block;
  585. if (offset_parent)
  586. {
  587. using namespace Style;
  588. Position position_property = GetPosition();
  589. const Box& parent_box = offset_parent->GetBox();
  590. if (position_property == Position::Static || position_property == Position::Relative)
  591. {
  592. containing_block = parent_box.GetSize();
  593. containing_block.x -= meta->scroll.GetScrollbarSize(ElementScroll::VERTICAL);
  594. containing_block.y -= meta->scroll.GetScrollbarSize(ElementScroll::HORIZONTAL);
  595. }
  596. else if (position_property == Position::Absolute || position_property == Position::Fixed)
  597. {
  598. containing_block = parent_box.GetSize(BoxArea::Padding);
  599. }
  600. }
  601. else if (Context* context = GetContext())
  602. {
  603. containing_block = Vector2f(context->GetDimensions());
  604. }
  605. return containing_block;
  606. }
  607. Style::Position Element::GetPosition()
  608. {
  609. return meta->computed_values.position();
  610. }
  611. Style::Float Element::GetFloat()
  612. {
  613. return meta->computed_values.float_();
  614. }
  615. Style::Display Element::GetDisplay()
  616. {
  617. return meta->computed_values.display();
  618. }
  619. float Element::GetLineHeight()
  620. {
  621. return meta->computed_values.line_height().value;
  622. }
  623. const TransformState* Element::GetTransformState() const noexcept
  624. {
  625. return transform_state.get();
  626. }
  627. bool Element::Project(Vector2f& point) const noexcept
  628. {
  629. if (!transform_state || !transform_state->GetTransform())
  630. return true;
  631. // The input point is in window coordinates. Need to find the projection of the point onto the current element plane,
  632. // taking into account the full transform applied to the element.
  633. if (const Matrix4f* inv_transform = transform_state->GetInverseTransform())
  634. {
  635. // Pick two points forming a line segment perpendicular to the window.
  636. Vector4f window_points[2] = {{point.x, point.y, -10, 1}, {point.x, point.y, 10, 1}};
  637. // Project them into the local element space.
  638. window_points[0] = *inv_transform * window_points[0];
  639. window_points[1] = *inv_transform * window_points[1];
  640. Vector3f local_points[2] = {window_points[0].PerspectiveDivide(), window_points[1].PerspectiveDivide()};
  641. // Construct a ray from the two projected points in the local space of the current element.
  642. // Find the intersection with the z=0 plane to produce our destination point.
  643. Vector3f ray = local_points[1] - local_points[0];
  644. // Only continue if we are not close to parallel with the plane.
  645. if (std::fabs(ray.z) > 1.0f)
  646. {
  647. // Solving the line equation p = p0 + t*ray for t, knowing that p.z = 0, produces the following.
  648. float t = -local_points[0].z / ray.z;
  649. Vector3f p = local_points[0] + ray * t;
  650. point = Vector2f(p.x, p.y);
  651. return true;
  652. }
  653. }
  654. // The transformation matrix is either singular, or the ray is parallel to the element's plane.
  655. return false;
  656. }
  657. PropertiesIteratorView Element::IterateLocalProperties() const
  658. {
  659. return PropertiesIteratorView(MakeUnique<PropertiesIterator>(meta->style.Iterate()));
  660. }
  661. void Element::SetPseudoClass(const String& pseudo_class, bool activate)
  662. {
  663. if (meta->style.SetPseudoClass(pseudo_class, activate, false))
  664. {
  665. // Include siblings in case of RCSS presence of sibling combinators '+', '~'.
  666. DirtyDefinition(DirtyNodes::SelfAndSiblings);
  667. OnPseudoClassChange(pseudo_class, activate);
  668. }
  669. }
  670. bool Element::IsPseudoClassSet(const String& pseudo_class) const
  671. {
  672. return meta->style.IsPseudoClassSet(pseudo_class);
  673. }
  674. bool Element::ArePseudoClassesSet(const StringList& pseudo_classes) const
  675. {
  676. for (const String& pseudo_class : pseudo_classes)
  677. {
  678. if (!IsPseudoClassSet(pseudo_class))
  679. return false;
  680. }
  681. return true;
  682. }
  683. StringList Element::GetActivePseudoClasses() const
  684. {
  685. const PseudoClassMap& pseudo_classes = meta->style.GetActivePseudoClasses();
  686. StringList names;
  687. names.reserve(pseudo_classes.size());
  688. for (auto& pseudo_class : pseudo_classes)
  689. {
  690. names.push_back(pseudo_class.first);
  691. }
  692. return names;
  693. }
  694. void Element::OverridePseudoClass(Element* element, const String& pseudo_class, bool activate)
  695. {
  696. RMLUI_ASSERT(element);
  697. element->GetStyle()->SetPseudoClass(pseudo_class, activate, true);
  698. }
  699. Variant* Element::GetAttribute(const String& name)
  700. {
  701. return GetIf(attributes, name);
  702. }
  703. const Variant* Element::GetAttribute(const String& name) const
  704. {
  705. return GetIf(attributes, name);
  706. }
  707. bool Element::HasAttribute(const String& name) const
  708. {
  709. return attributes.find(name) != attributes.end();
  710. }
  711. void Element::RemoveAttribute(const String& name)
  712. {
  713. auto it = attributes.find(name);
  714. if (it != attributes.end())
  715. {
  716. attributes.erase(it);
  717. ElementAttributes changed_attributes;
  718. changed_attributes.emplace(name, Variant());
  719. OnAttributeChange(changed_attributes);
  720. }
  721. }
  722. Element* Element::GetFocusLeafNode()
  723. {
  724. // If there isn't a focus, then we are the leaf.
  725. if (!focus)
  726. {
  727. return this;
  728. }
  729. // Recurse down the tree until we found the leaf focus element
  730. Element* focus_element = focus;
  731. while (focus_element->focus)
  732. focus_element = focus_element->focus;
  733. return focus_element;
  734. }
  735. Context* Element::GetContext() const
  736. {
  737. ElementDocument* document = GetOwnerDocument();
  738. if (document != nullptr)
  739. return document->GetContext();
  740. return nullptr;
  741. }
  742. RenderManager* Element::GetRenderManager() const
  743. {
  744. if (Context* context = GetContext())
  745. return &context->GetRenderManager();
  746. return nullptr;
  747. }
  748. void Element::SetAttributes(const ElementAttributes& _attributes)
  749. {
  750. attributes.reserve(attributes.size() + _attributes.size());
  751. for (auto& pair : _attributes)
  752. attributes[pair.first] = pair.second;
  753. OnAttributeChange(_attributes);
  754. }
  755. int Element::GetNumAttributes() const
  756. {
  757. return (int)attributes.size();
  758. }
  759. const String& Element::GetTagName() const
  760. {
  761. return tag;
  762. }
  763. const String& Element::GetId() const
  764. {
  765. return id;
  766. }
  767. void Element::SetId(const String& _id)
  768. {
  769. SetAttribute("id", _id);
  770. }
  771. float Element::GetAbsoluteLeft()
  772. {
  773. return GetAbsoluteOffset(BoxArea::Border).x;
  774. }
  775. float Element::GetAbsoluteTop()
  776. {
  777. return GetAbsoluteOffset(BoxArea::Border).y;
  778. }
  779. float Element::GetClientLeft()
  780. {
  781. return GetBox().GetPosition(BoxArea::Padding).x;
  782. }
  783. float Element::GetClientTop()
  784. {
  785. return GetBox().GetPosition(BoxArea::Padding).y;
  786. }
  787. float Element::GetClientWidth()
  788. {
  789. return GetBox().GetSize(BoxArea::Padding).x - meta->scroll.GetScrollbarSize(ElementScroll::VERTICAL);
  790. }
  791. float Element::GetClientHeight()
  792. {
  793. return GetBox().GetSize(BoxArea::Padding).y - meta->scroll.GetScrollbarSize(ElementScroll::HORIZONTAL);
  794. }
  795. Element* Element::GetOffsetParent()
  796. {
  797. return offset_parent;
  798. }
  799. float Element::GetOffsetLeft()
  800. {
  801. return relative_offset_base.x + relative_offset_position.x;
  802. }
  803. float Element::GetOffsetTop()
  804. {
  805. return relative_offset_base.y + relative_offset_position.y;
  806. }
  807. float Element::GetOffsetWidth()
  808. {
  809. return GetBox().GetSize(BoxArea::Border).x;
  810. }
  811. float Element::GetOffsetHeight()
  812. {
  813. return GetBox().GetSize(BoxArea::Border).y;
  814. }
  815. float Element::GetScrollLeft()
  816. {
  817. return scroll_offset.x;
  818. }
  819. void Element::SetScrollLeft(float scroll_left)
  820. {
  821. const float new_offset = Math::Round(Math::Clamp(scroll_left, 0.0f, GetScrollWidth() - GetClientWidth()));
  822. if (new_offset != scroll_offset.x)
  823. {
  824. scroll_offset.x = new_offset;
  825. meta->scroll.UpdateScrollbar(ElementScroll::HORIZONTAL);
  826. DirtyAbsoluteOffset();
  827. DispatchEvent(EventId::Scroll, Dictionary());
  828. }
  829. }
  830. float Element::GetScrollTop()
  831. {
  832. return scroll_offset.y;
  833. }
  834. void Element::SetScrollTop(float scroll_top)
  835. {
  836. const float new_offset = Math::Round(Math::Clamp(Math::Round(scroll_top), 0.0f, GetScrollHeight() - GetClientHeight()));
  837. if (new_offset != scroll_offset.y)
  838. {
  839. scroll_offset.y = new_offset;
  840. meta->scroll.UpdateScrollbar(ElementScroll::VERTICAL);
  841. DirtyAbsoluteOffset();
  842. DispatchEvent(EventId::Scroll, Dictionary());
  843. }
  844. }
  845. float Element::GetScrollWidth()
  846. {
  847. return Math::Max(scrollable_overflow_rectangle.x, GetClientWidth());
  848. }
  849. float Element::GetScrollHeight()
  850. {
  851. return Math::Max(scrollable_overflow_rectangle.y, GetClientHeight());
  852. }
  853. ElementStyle* Element::GetStyle() const
  854. {
  855. return &meta->style;
  856. }
  857. ElementDocument* Element::GetOwnerDocument() const
  858. {
  859. #ifdef RMLUI_DEBUG
  860. if (parent && !owner_document)
  861. {
  862. // Since we have a parent but no owner_document, then we must be a 'loose' element -- that is, constructed
  863. // outside of a document and not attached to a child of any element in the hierarchy of a document.
  864. // This check ensures that we didn't just forget to set the owner document.
  865. RMLUI_ASSERT(!parent->GetOwnerDocument());
  866. }
  867. #endif
  868. return owner_document;
  869. }
  870. Element* Element::GetParentNode() const
  871. {
  872. return parent;
  873. }
  874. Element* Element::Closest(const String& selectors) const
  875. {
  876. StyleSheetNode root_node;
  877. StyleSheetNodeListRaw leaf_nodes = StyleSheetParser::ConstructNodes(root_node, selectors);
  878. if (leaf_nodes.empty())
  879. {
  880. Log::Message(Log::LT_WARNING, "Query selector '%s' is empty. In element %s", selectors.c_str(), GetAddress().c_str());
  881. return nullptr;
  882. }
  883. Element* parent = GetParentNode();
  884. while (parent)
  885. {
  886. for (const StyleSheetNode* node : leaf_nodes)
  887. {
  888. if (node->IsApplicable(parent, this))
  889. {
  890. return parent;
  891. }
  892. }
  893. parent = parent->GetParentNode();
  894. }
  895. return nullptr;
  896. }
  897. Element* Element::GetNextSibling() const
  898. {
  899. if (parent == nullptr)
  900. return nullptr;
  901. for (size_t i = 0; i < parent->children.size() - (parent->num_non_dom_children + 1); i++)
  902. {
  903. if (parent->children[i].get() == this)
  904. return parent->children[i + 1].get();
  905. }
  906. return nullptr;
  907. }
  908. Element* Element::GetPreviousSibling() const
  909. {
  910. if (parent == nullptr)
  911. return nullptr;
  912. for (size_t i = 1; i < parent->children.size() - parent->num_non_dom_children; i++)
  913. {
  914. if (parent->children[i].get() == this)
  915. return parent->children[i - 1].get();
  916. }
  917. return nullptr;
  918. }
  919. Element* Element::GetFirstChild() const
  920. {
  921. if (GetNumChildren() > 0)
  922. return children[0].get();
  923. return nullptr;
  924. }
  925. Element* Element::GetLastChild() const
  926. {
  927. if (GetNumChildren() > 0)
  928. return (children.end() - (num_non_dom_children + 1))->get();
  929. return nullptr;
  930. }
  931. Element* Element::GetChild(int index) const
  932. {
  933. if (index < 0 || index >= (int)children.size())
  934. return nullptr;
  935. return children[index].get();
  936. }
  937. int Element::GetNumChildren(bool include_non_dom_elements) const
  938. {
  939. return (int)children.size() - (include_non_dom_elements ? 0 : num_non_dom_children);
  940. }
  941. void Element::GetInnerRML(String& content) const
  942. {
  943. for (int i = 0; i < GetNumChildren(); i++)
  944. {
  945. children[i]->GetRML(content);
  946. }
  947. }
  948. String Element::GetInnerRML() const
  949. {
  950. String result;
  951. GetInnerRML(result);
  952. return result;
  953. }
  954. void Element::SetInnerRML(const String& rml)
  955. {
  956. RMLUI_ZoneScopedC(0x6495ED);
  957. // Remove all DOM children.
  958. while ((int)children.size() > num_non_dom_children)
  959. RemoveChild(children.front().get());
  960. if (!rml.empty())
  961. Factory::InstanceElementText(this, rml);
  962. }
  963. bool Element::Focus(bool focus_visible)
  964. {
  965. // Are we allowed focus?
  966. Style::Focus focus_property = meta->computed_values.focus();
  967. if (focus_property == Style::Focus::None)
  968. return false;
  969. // Ask our context if we can switch focus.
  970. Context* context = GetContext();
  971. if (context == nullptr)
  972. return false;
  973. if (!context->OnFocusChange(this, focus_visible))
  974. return false;
  975. // Set this as the end of the focus chain.
  976. focus = nullptr;
  977. // Update the focus chain up the hierarchy.
  978. Element* element = this;
  979. while (Element* parent = element->GetParentNode())
  980. {
  981. parent->focus = element;
  982. element = parent;
  983. }
  984. return true;
  985. }
  986. void Element::Blur()
  987. {
  988. if (parent)
  989. {
  990. Context* context = GetContext();
  991. if (context == nullptr)
  992. return;
  993. if (context->GetFocusElement() == this)
  994. {
  995. parent->Focus();
  996. }
  997. else if (parent->focus == this)
  998. {
  999. parent->focus = nullptr;
  1000. }
  1001. }
  1002. }
  1003. void Element::Click()
  1004. {
  1005. Context* context = GetContext();
  1006. if (context == nullptr)
  1007. return;
  1008. context->GenerateClickEvent(this);
  1009. }
  1010. void Element::AddEventListener(const String& event, EventListener* listener, const bool in_capture_phase)
  1011. {
  1012. const EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  1013. meta->event_dispatcher.AttachEvent(id, listener, in_capture_phase);
  1014. }
  1015. void Element::AddEventListener(const EventId id, EventListener* listener, const bool in_capture_phase)
  1016. {
  1017. meta->event_dispatcher.AttachEvent(id, listener, in_capture_phase);
  1018. }
  1019. void Element::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
  1020. {
  1021. EventId id = EventSpecificationInterface::GetIdOrInsert(event);
  1022. meta->event_dispatcher.DetachEvent(id, listener, in_capture_phase);
  1023. }
  1024. void Element::RemoveEventListener(EventId id, EventListener* listener, bool in_capture_phase)
  1025. {
  1026. meta->event_dispatcher.DetachEvent(id, listener, in_capture_phase);
  1027. }
  1028. bool Element::DispatchEvent(const String& type, const Dictionary& parameters)
  1029. {
  1030. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  1031. return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, specification.interruptible, specification.bubbles,
  1032. specification.default_action_phase);
  1033. }
  1034. bool Element::DispatchEvent(const String& type, const Dictionary& parameters, bool interruptible, bool bubbles)
  1035. {
  1036. const EventSpecification& specification = EventSpecificationInterface::GetOrInsert(type);
  1037. return EventDispatcher::DispatchEvent(this, specification.id, type, parameters, interruptible, bubbles, specification.default_action_phase);
  1038. }
  1039. bool Element::DispatchEvent(EventId id, const Dictionary& parameters)
  1040. {
  1041. const EventSpecification& specification = EventSpecificationInterface::Get(id);
  1042. return EventDispatcher::DispatchEvent(this, specification.id, specification.type, parameters, specification.interruptible, specification.bubbles,
  1043. specification.default_action_phase);
  1044. }
  1045. void Element::ScrollIntoView(const ScrollIntoViewOptions options)
  1046. {
  1047. const Vector2f size = main_box.GetSize(BoxArea::Border);
  1048. ScrollBehavior scroll_behavior = options.behavior;
  1049. for (Element* scroll_parent = parent; scroll_parent; scroll_parent = scroll_parent->GetParentNode())
  1050. {
  1051. using Style::Overflow;
  1052. const ComputedValues& computed = scroll_parent->GetComputedValues();
  1053. const bool scrollable_box_x = (computed.overflow_x() != Overflow::Visible && computed.overflow_x() != Overflow::Hidden);
  1054. const bool scrollable_box_y = (computed.overflow_y() != Overflow::Visible && computed.overflow_y() != Overflow::Hidden);
  1055. const Vector2f parent_scroll_size = {scroll_parent->GetScrollWidth(), scroll_parent->GetScrollHeight()};
  1056. const Vector2f parent_client_size = {scroll_parent->GetClientWidth(), scroll_parent->GetClientHeight()};
  1057. if ((scrollable_box_x && parent_scroll_size.x > parent_client_size.x) || (scrollable_box_y && parent_scroll_size.y > parent_client_size.y))
  1058. {
  1059. const Vector2f relative_offset = scroll_parent->GetAbsoluteOffset(BoxArea::Border) - GetAbsoluteOffset(BoxArea::Border);
  1060. const Vector2f old_scroll_offset = {scroll_parent->GetScrollLeft(), scroll_parent->GetScrollTop()};
  1061. const Vector2f parent_client_offset = {scroll_parent->GetClientLeft(), scroll_parent->GetClientTop()};
  1062. const Vector2f delta_scroll_offset_start = parent_client_offset - relative_offset;
  1063. const Vector2f delta_scroll_offset_end = delta_scroll_offset_start + size - parent_client_size;
  1064. Vector2f scroll_delta = {
  1065. scrollable_box_x ? GetScrollOffsetDelta(options.horizontal, delta_scroll_offset_start.x, delta_scroll_offset_end.x) : 0.f,
  1066. scrollable_box_y ? GetScrollOffsetDelta(options.vertical, delta_scroll_offset_start.y, delta_scroll_offset_end.y) : 0.f,
  1067. };
  1068. scroll_parent->ScrollTo(old_scroll_offset + scroll_delta, scroll_behavior);
  1069. // Currently, only a single scrollable parent can be smooth scrolled at a time, so any other parents must be instant scrolled.
  1070. scroll_behavior = ScrollBehavior::Instant;
  1071. }
  1072. if ((scrollable_box_x || scrollable_box_y) && options.parentage == ScrollParentage::Closest)
  1073. break;
  1074. }
  1075. }
  1076. void Element::ScrollIntoView(bool align_with_top)
  1077. {
  1078. ScrollIntoViewOptions options;
  1079. options.vertical = (align_with_top ? ScrollAlignment::Start : ScrollAlignment::End);
  1080. options.horizontal = ScrollAlignment::Nearest;
  1081. ScrollIntoView(options);
  1082. }
  1083. void Element::ScrollTo(Vector2f offset, ScrollBehavior behavior)
  1084. {
  1085. if (behavior != ScrollBehavior::Instant)
  1086. {
  1087. if (Context* context = GetContext())
  1088. {
  1089. context->PerformSmoothscrollOnTarget(this, offset - scroll_offset, behavior);
  1090. return;
  1091. }
  1092. }
  1093. SetScrollLeft(offset.x);
  1094. SetScrollTop(offset.y);
  1095. }
  1096. Element* Element::AppendChild(ElementPtr child, bool dom_element)
  1097. {
  1098. RMLUI_ASSERT(child);
  1099. Element* child_ptr = child.get();
  1100. if (dom_element)
  1101. children.insert(children.end() - num_non_dom_children, std::move(child));
  1102. else
  1103. {
  1104. children.push_back(std::move(child));
  1105. num_non_dom_children++;
  1106. }
  1107. // Set parent just after inserting into children. This allows us to eg. get our previous sibling in SetParent.
  1108. child_ptr->SetParent(this);
  1109. Element* ancestor = child_ptr;
  1110. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1111. ancestor->OnChildAdd(child_ptr);
  1112. DirtyStackingContext();
  1113. // Not only does the element definition of the newly inserted element need to be dirtied, but also our own definition and implicitly all of our
  1114. // children's. This ensures correct styles being applied in the presence of tree-structural selectors such as ':first-child'.
  1115. DirtyDefinition(DirtyNodes::Self);
  1116. if (dom_element)
  1117. DirtyLayout();
  1118. return child_ptr;
  1119. }
  1120. Element* Element::InsertBefore(ElementPtr child, Element* adjacent_element)
  1121. {
  1122. RMLUI_ASSERT(child);
  1123. // Find the position in the list of children of the adjacent element. If
  1124. // it's nullptr or we can't find it, then we insert it at the end of the dom
  1125. // children, as a dom element.
  1126. size_t child_index = 0;
  1127. bool found_child = false;
  1128. if (adjacent_element)
  1129. {
  1130. for (child_index = 0; child_index < children.size(); child_index++)
  1131. {
  1132. if (children[child_index].get() == adjacent_element)
  1133. {
  1134. found_child = true;
  1135. break;
  1136. }
  1137. }
  1138. }
  1139. Element* child_ptr = nullptr;
  1140. if (found_child)
  1141. {
  1142. child_ptr = child.get();
  1143. if ((int)child_index >= GetNumChildren())
  1144. num_non_dom_children++;
  1145. else
  1146. DirtyLayout();
  1147. children.insert(children.begin() + child_index, std::move(child));
  1148. child_ptr->SetParent(this);
  1149. Element* ancestor = child_ptr;
  1150. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1151. ancestor->OnChildAdd(child_ptr);
  1152. DirtyStackingContext();
  1153. DirtyDefinition(DirtyNodes::Self);
  1154. }
  1155. else
  1156. {
  1157. child_ptr = AppendChild(std::move(child));
  1158. }
  1159. return child_ptr;
  1160. }
  1161. ElementPtr Element::ReplaceChild(ElementPtr inserted_element, Element* replaced_element)
  1162. {
  1163. RMLUI_ASSERT(inserted_element);
  1164. auto insertion_point = children.begin();
  1165. while (insertion_point != children.end() && insertion_point->get() != replaced_element)
  1166. {
  1167. ++insertion_point;
  1168. }
  1169. Element* inserted_element_ptr = inserted_element.get();
  1170. if (insertion_point == children.end())
  1171. {
  1172. AppendChild(std::move(inserted_element));
  1173. return nullptr;
  1174. }
  1175. children.insert(insertion_point, std::move(inserted_element));
  1176. inserted_element_ptr->SetParent(this);
  1177. ElementPtr result = RemoveChild(replaced_element);
  1178. Element* ancestor = inserted_element_ptr;
  1179. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1180. ancestor->OnChildAdd(inserted_element_ptr);
  1181. return result;
  1182. }
  1183. ElementPtr Element::RemoveChild(Element* child)
  1184. {
  1185. size_t child_index = 0;
  1186. for (auto itr = children.begin(); itr != children.end(); ++itr)
  1187. {
  1188. // Add the element to the delete list
  1189. if (itr->get() == child)
  1190. {
  1191. Element* ancestor = child;
  1192. for (int i = 0; i <= ChildNotifyLevels && ancestor; i++, ancestor = ancestor->GetParentNode())
  1193. ancestor->OnChildRemove(child);
  1194. if (child_index >= children.size() - num_non_dom_children)
  1195. num_non_dom_children--;
  1196. ElementPtr detached_child = std::move(*itr);
  1197. children.erase(itr);
  1198. // Remove the child element as the focused child of this element.
  1199. if (child == focus)
  1200. {
  1201. focus = nullptr;
  1202. // If this child (or a descendant of this child) is the context's currently
  1203. // focused element, set the focus to us instead.
  1204. if (Context* context = GetContext())
  1205. {
  1206. Element* focus_element = context->GetFocusElement();
  1207. while (focus_element)
  1208. {
  1209. if (focus_element == child)
  1210. {
  1211. Focus();
  1212. break;
  1213. }
  1214. focus_element = focus_element->GetParentNode();
  1215. }
  1216. }
  1217. }
  1218. detached_child->SetParent(nullptr);
  1219. DirtyLayout();
  1220. DirtyStackingContext();
  1221. DirtyDefinition(DirtyNodes::Self);
  1222. return detached_child;
  1223. }
  1224. child_index++;
  1225. }
  1226. return nullptr;
  1227. }
  1228. bool Element::HasChildNodes() const
  1229. {
  1230. return (int)children.size() > num_non_dom_children;
  1231. }
  1232. Element* Element::GetElementById(const String& id)
  1233. {
  1234. // Check for special-case tokens.
  1235. if (id == "#self")
  1236. return this;
  1237. else if (id == "#document")
  1238. return GetOwnerDocument();
  1239. else if (id == "#parent")
  1240. return this->parent;
  1241. else
  1242. {
  1243. Element* search_root = GetOwnerDocument();
  1244. if (search_root == nullptr)
  1245. search_root = this;
  1246. return ElementUtilities::GetElementById(search_root, id);
  1247. }
  1248. }
  1249. void Element::GetElementsByTagName(ElementList& elements, const String& tag)
  1250. {
  1251. return ElementUtilities::GetElementsByTagName(elements, this, tag);
  1252. }
  1253. void Element::GetElementsByClassName(ElementList& elements, const String& class_name)
  1254. {
  1255. return ElementUtilities::GetElementsByClassName(elements, this, class_name);
  1256. }
  1257. static Element* QuerySelectorMatchRecursive(const StyleSheetNodeListRaw& nodes, Element* element, Element* scope)
  1258. {
  1259. const int num_children = element->GetNumChildren();
  1260. for (int i = 0; i < num_children; i++)
  1261. {
  1262. Element* child = element->GetChild(i);
  1263. if (child->GetTagName() == "#text")
  1264. continue;
  1265. for (const StyleSheetNode* node : nodes)
  1266. {
  1267. if (node->IsApplicable(child, scope))
  1268. return child;
  1269. }
  1270. Element* matching_element = QuerySelectorMatchRecursive(nodes, child, scope);
  1271. if (matching_element)
  1272. return matching_element;
  1273. }
  1274. return nullptr;
  1275. }
  1276. static void QuerySelectorAllMatchRecursive(ElementList& matching_elements, const StyleSheetNodeListRaw& nodes, Element* element, Element* scope)
  1277. {
  1278. const int num_children = element->GetNumChildren();
  1279. for (int i = 0; i < num_children; i++)
  1280. {
  1281. Element* child = element->GetChild(i);
  1282. if (child->GetTagName() == "#text")
  1283. continue;
  1284. for (const StyleSheetNode* node : nodes)
  1285. {
  1286. if (node->IsApplicable(child, scope))
  1287. {
  1288. matching_elements.push_back(child);
  1289. break;
  1290. }
  1291. }
  1292. QuerySelectorAllMatchRecursive(matching_elements, nodes, child, scope);
  1293. }
  1294. }
  1295. Element* Element::QuerySelector(const String& selectors)
  1296. {
  1297. StyleSheetNode root_node;
  1298. StyleSheetNodeListRaw leaf_nodes = StyleSheetParser::ConstructNodes(root_node, selectors);
  1299. if (leaf_nodes.empty())
  1300. {
  1301. Log::Message(Log::LT_WARNING, "Query selector '%s' is empty. In element %s", selectors.c_str(), GetAddress().c_str());
  1302. return nullptr;
  1303. }
  1304. return QuerySelectorMatchRecursive(leaf_nodes, this, this);
  1305. }
  1306. void Element::QuerySelectorAll(ElementList& elements, const String& selectors)
  1307. {
  1308. StyleSheetNode root_node;
  1309. StyleSheetNodeListRaw leaf_nodes = StyleSheetParser::ConstructNodes(root_node, selectors);
  1310. if (leaf_nodes.empty())
  1311. {
  1312. Log::Message(Log::LT_WARNING, "Query selector '%s' is empty. In element %s", selectors.c_str(), GetAddress().c_str());
  1313. return;
  1314. }
  1315. QuerySelectorAllMatchRecursive(elements, leaf_nodes, this, this);
  1316. }
  1317. bool Element::Matches(const String& selectors)
  1318. {
  1319. StyleSheetNode root_node;
  1320. StyleSheetNodeListRaw leaf_nodes = StyleSheetParser::ConstructNodes(root_node, selectors);
  1321. if (leaf_nodes.empty())
  1322. {
  1323. Log::Message(Log::LT_WARNING, "Query selector '%s' is empty. In element %s", selectors.c_str(), GetAddress().c_str());
  1324. return false;
  1325. }
  1326. for (const StyleSheetNode* node : leaf_nodes)
  1327. {
  1328. if (node->IsApplicable(this, this))
  1329. {
  1330. return true;
  1331. }
  1332. }
  1333. return false;
  1334. }
  1335. bool Element::Contains(Element* element) const
  1336. {
  1337. while (element)
  1338. {
  1339. if (element == this)
  1340. return true;
  1341. element = element->GetParentNode();
  1342. }
  1343. return false;
  1344. }
  1345. EventDispatcher* Element::GetEventDispatcher() const
  1346. {
  1347. return &meta->event_dispatcher;
  1348. }
  1349. String Element::GetEventDispatcherSummary() const
  1350. {
  1351. return meta->event_dispatcher.ToString();
  1352. }
  1353. ElementBackgroundBorder* Element::GetElementBackgroundBorder() const
  1354. {
  1355. return &meta->background_border;
  1356. }
  1357. ElementScroll* Element::GetElementScroll() const
  1358. {
  1359. return &meta->scroll;
  1360. }
  1361. DataModel* Element::GetDataModel() const
  1362. {
  1363. return data_model;
  1364. }
  1365. void Element::SetInstancer(ElementInstancer* _instancer)
  1366. {
  1367. // Only record the first instancer being set as some instancers call other instancers to do their dirty work, in
  1368. // which case we don't want to update the lowest level instancer.
  1369. if (!instancer)
  1370. {
  1371. instancer = _instancer;
  1372. }
  1373. }
  1374. void Element::ForceLocalStackingContext()
  1375. {
  1376. local_stacking_context_forced = true;
  1377. local_stacking_context = true;
  1378. DirtyStackingContext();
  1379. }
  1380. void Element::OnUpdate() {}
  1381. void Element::OnRender() {}
  1382. void Element::OnResize() {}
  1383. void Element::OnLayout() {}
  1384. void Element::OnDpRatioChange() {}
  1385. void Element::OnStyleSheetChange() {}
  1386. void Element::OnAttributeChange(const ElementAttributes& changed_attributes)
  1387. {
  1388. for (const auto& element_attribute : changed_attributes)
  1389. {
  1390. const auto& attribute = element_attribute.first;
  1391. const auto& value = element_attribute.second;
  1392. if (attribute == "id")
  1393. {
  1394. id = value.Get<String>();
  1395. }
  1396. else if (attribute == "class")
  1397. {
  1398. meta->style.SetClassNames(value.Get<String>());
  1399. }
  1400. else if (((attribute == "colspan" || attribute == "rowspan") && meta->computed_values.display() == Style::Display::TableCell) ||
  1401. (attribute == "span" &&
  1402. (meta->computed_values.display() == Style::Display::TableColumn ||
  1403. meta->computed_values.display() == Style::Display::TableColumnGroup)))
  1404. {
  1405. DirtyLayout();
  1406. }
  1407. else if (attribute.size() > 2 && attribute[0] == 'o' && attribute[1] == 'n')
  1408. {
  1409. static constexpr bool IN_CAPTURE_PHASE = false;
  1410. auto& attribute_event_listeners = meta->attribute_event_listeners;
  1411. auto& event_dispatcher = meta->event_dispatcher;
  1412. const auto event_id = EventSpecificationInterface::GetIdOrInsert(attribute.substr(2));
  1413. const auto remove_event_listener_if_exists = [&attribute_event_listeners, &event_dispatcher, event_id]() {
  1414. const auto listener_it = attribute_event_listeners.find(event_id);
  1415. if (listener_it != attribute_event_listeners.cend())
  1416. {
  1417. event_dispatcher.DetachEvent(event_id, listener_it->second, IN_CAPTURE_PHASE);
  1418. attribute_event_listeners.erase(listener_it);
  1419. }
  1420. };
  1421. if (value.GetType() == Variant::Type::STRING)
  1422. {
  1423. remove_event_listener_if_exists();
  1424. const auto value_as_string = value.Get<String>();
  1425. auto insertion_result = attribute_event_listeners.emplace(event_id, Factory::InstanceEventListener(value_as_string, this));
  1426. if (auto* listener = insertion_result.first->second)
  1427. event_dispatcher.AttachEvent(event_id, listener, IN_CAPTURE_PHASE);
  1428. }
  1429. else if (value.GetType() == Variant::Type::NONE)
  1430. remove_event_listener_if_exists();
  1431. }
  1432. else if (attribute == "style")
  1433. {
  1434. if (value.GetType() == Variant::STRING)
  1435. {
  1436. PropertyDictionary properties;
  1437. StyleSheetParser parser;
  1438. parser.ParseProperties(properties, value.GetReference<String>());
  1439. for (const auto& name_value : properties.GetProperties())
  1440. meta->style.SetProperty(name_value.first, name_value.second);
  1441. }
  1442. else if (value.GetType() != Variant::NONE)
  1443. Log::Message(Log::LT_WARNING, "Invalid 'style' attribute, string type required. In element: %s", GetAddress().c_str());
  1444. }
  1445. else if (attribute == "lang")
  1446. {
  1447. if (value.GetType() == Variant::STRING)
  1448. meta->style.SetProperty(PropertyId::RmlUi_Language, Property(value.GetReference<String>(), Unit::STRING));
  1449. else if (value.GetType() != Variant::NONE)
  1450. Log::Message(Log::LT_WARNING, "Invalid 'lang' attribute, string type required. In element: %s", GetAddress().c_str());
  1451. }
  1452. else if (attribute == "dir")
  1453. {
  1454. if (value.GetType() == Variant::STRING)
  1455. {
  1456. const String& dir_value = value.GetReference<String>();
  1457. if (dir_value == "auto")
  1458. meta->style.SetProperty(PropertyId::RmlUi_Direction, Property(Style::Direction::Auto));
  1459. else if (dir_value == "ltr")
  1460. meta->style.SetProperty(PropertyId::RmlUi_Direction, Property(Style::Direction::Ltr));
  1461. else if (dir_value == "rtl")
  1462. meta->style.SetProperty(PropertyId::RmlUi_Direction, Property(Style::Direction::Rtl));
  1463. else
  1464. Log::Message(Log::LT_WARNING, "Invalid 'dir' attribute '%s', value must be 'auto', 'ltr', or 'rtl'. In element: %s",
  1465. dir_value.c_str(), GetAddress().c_str());
  1466. }
  1467. else if (value.GetType() != Variant::NONE)
  1468. Log::Message(Log::LT_WARNING, "Invalid 'dir' attribute, string type required. In element: %s", GetAddress().c_str());
  1469. }
  1470. }
  1471. // Any change to the attributes may affect which styles apply to the current element, in particular due to attribute selectors, ID selectors, and
  1472. // class selectors. This can further affect all siblings or descendants due to sibling or descendant combinators.
  1473. DirtyDefinition(DirtyNodes::SelfAndSiblings);
  1474. }
  1475. void Element::OnPropertyChange(const PropertyIdSet& changed_properties)
  1476. {
  1477. RMLUI_ZoneScoped;
  1478. const bool top_right_bottom_left_changed = ( //
  1479. changed_properties.Contains(PropertyId::Top) || //
  1480. changed_properties.Contains(PropertyId::Right) || //
  1481. changed_properties.Contains(PropertyId::Bottom) || //
  1482. changed_properties.Contains(PropertyId::Left) //
  1483. );
  1484. // See if the document layout needs to be updated.
  1485. if (!IsLayoutDirty())
  1486. {
  1487. // Force a relayout if any of the changed properties require it.
  1488. const PropertyIdSet changed_properties_forcing_layout =
  1489. (changed_properties & StyleSheetSpecification::GetRegisteredPropertiesForcingLayout());
  1490. if (!changed_properties_forcing_layout.Empty())
  1491. {
  1492. DirtyLayout();
  1493. }
  1494. else if (top_right_bottom_left_changed)
  1495. {
  1496. // Normally, the position properties only affect the position of the element and not the layout. Thus, these properties are not registered
  1497. // as affecting layout. However, when absolutely positioned elements with both left & right, or top & bottom are set to definite values,
  1498. // they affect the size of the element and thereby also the layout. This layout-dirtying condition needs to be registered manually.
  1499. using namespace Style;
  1500. const ComputedValues& computed = GetComputedValues();
  1501. const bool absolutely_positioned = (computed.position() == Position::Absolute || computed.position() == Position::Fixed);
  1502. const bool sized_width =
  1503. (computed.width().type == Width::Auto && computed.left().type != Left::Auto && computed.right().type != Right::Auto);
  1504. const bool sized_height =
  1505. (computed.height().type == Height::Auto && computed.top().type != Top::Auto && computed.bottom().type != Bottom::Auto);
  1506. if (absolutely_positioned && (sized_width || sized_height))
  1507. DirtyLayout();
  1508. }
  1509. }
  1510. // Update the position.
  1511. if (top_right_bottom_left_changed)
  1512. {
  1513. UpdateOffset();
  1514. DirtyAbsoluteOffset();
  1515. }
  1516. // Update the visibility.
  1517. if (changed_properties.Contains(PropertyId::Visibility) || changed_properties.Contains(PropertyId::Display))
  1518. {
  1519. bool new_visibility =
  1520. (meta->computed_values.display() != Style::Display::None && meta->computed_values.visibility() == Style::Visibility::Visible);
  1521. if (visible != new_visibility)
  1522. {
  1523. visible = new_visibility;
  1524. if (parent != nullptr)
  1525. parent->DirtyStackingContext();
  1526. if (!visible)
  1527. Blur();
  1528. }
  1529. }
  1530. const bool border_radius_changed = ( //
  1531. changed_properties.Contains(PropertyId::BorderTopLeftRadius) || //
  1532. changed_properties.Contains(PropertyId::BorderTopRightRadius) || //
  1533. changed_properties.Contains(PropertyId::BorderBottomRightRadius) || //
  1534. changed_properties.Contains(PropertyId::BorderBottomLeftRadius) //
  1535. );
  1536. const bool filter_or_mask_changed = (changed_properties.Contains(PropertyId::Filter) || changed_properties.Contains(PropertyId::BackdropFilter) ||
  1537. changed_properties.Contains(PropertyId::MaskImage));
  1538. // Update the z-index and stacking context.
  1539. if (changed_properties.Contains(PropertyId::ZIndex) || filter_or_mask_changed)
  1540. {
  1541. const Style::ZIndex z_index_property = meta->computed_values.z_index();
  1542. const float new_z_index = (z_index_property.type == Style::ZIndex::Auto ? 0.f : z_index_property.value);
  1543. const bool enable_local_stacking_context = (z_index_property.type != Style::ZIndex::Auto || local_stacking_context_forced ||
  1544. meta->computed_values.has_filter() || meta->computed_values.has_backdrop_filter() || meta->computed_values.has_mask_image());
  1545. if (z_index != new_z_index || local_stacking_context != enable_local_stacking_context)
  1546. {
  1547. z_index = new_z_index;
  1548. if (local_stacking_context != enable_local_stacking_context)
  1549. {
  1550. local_stacking_context = enable_local_stacking_context;
  1551. // If we are no longer acting as a local stacking context, then we clear the list and are all set. Otherwise, we need to rebuild our
  1552. // local stacking context.
  1553. stacking_context.clear();
  1554. stacking_context_dirty = local_stacking_context;
  1555. }
  1556. // When our z-index or local stacking context changes, then we must dirty our parent stacking context so we are re-indexed.
  1557. if (parent)
  1558. parent->DirtyStackingContext();
  1559. }
  1560. }
  1561. // Dirty the background if it's changed.
  1562. if (border_radius_changed || //
  1563. changed_properties.Contains(PropertyId::BackgroundColor) || //
  1564. changed_properties.Contains(PropertyId::Opacity) || //
  1565. changed_properties.Contains(PropertyId::ImageColor) || //
  1566. changed_properties.Contains(PropertyId::BoxShadow)) //
  1567. {
  1568. meta->background_border.DirtyBackground();
  1569. }
  1570. // Dirty the border if it's changed.
  1571. if (border_radius_changed || //
  1572. changed_properties.Contains(PropertyId::BorderTopWidth) || //
  1573. changed_properties.Contains(PropertyId::BorderRightWidth) || //
  1574. changed_properties.Contains(PropertyId::BorderBottomWidth) || //
  1575. changed_properties.Contains(PropertyId::BorderLeftWidth) || //
  1576. changed_properties.Contains(PropertyId::BorderTopColor) || //
  1577. changed_properties.Contains(PropertyId::BorderRightColor) || //
  1578. changed_properties.Contains(PropertyId::BorderBottomColor) || //
  1579. changed_properties.Contains(PropertyId::BorderLeftColor) || //
  1580. changed_properties.Contains(PropertyId::Opacity))
  1581. {
  1582. meta->background_border.DirtyBorder();
  1583. }
  1584. // Dirty the effects if they've changed.
  1585. if (border_radius_changed || filter_or_mask_changed || changed_properties.Contains(PropertyId::Decorator))
  1586. {
  1587. meta->effects.DirtyEffects();
  1588. }
  1589. // Dirty the effects data when their visual looks may have changed.
  1590. if (border_radius_changed || //
  1591. changed_properties.Contains(PropertyId::Opacity) || //
  1592. changed_properties.Contains(PropertyId::ImageColor))
  1593. {
  1594. meta->effects.DirtyEffectsData();
  1595. }
  1596. // Check for `perspective' and `perspective-origin' changes
  1597. if (changed_properties.Contains(PropertyId::Perspective) || //
  1598. changed_properties.Contains(PropertyId::PerspectiveOriginX) || //
  1599. changed_properties.Contains(PropertyId::PerspectiveOriginY))
  1600. {
  1601. DirtyTransformState(true, false);
  1602. }
  1603. // Check for `transform' and `transform-origin' changes
  1604. if (changed_properties.Contains(PropertyId::Transform) || //
  1605. changed_properties.Contains(PropertyId::TransformOriginX) || //
  1606. changed_properties.Contains(PropertyId::TransformOriginY) || //
  1607. changed_properties.Contains(PropertyId::TransformOriginZ))
  1608. {
  1609. DirtyTransformState(false, true);
  1610. }
  1611. // Check for `animation' changes
  1612. if (changed_properties.Contains(PropertyId::Animation))
  1613. {
  1614. dirty_animation = true;
  1615. }
  1616. // Check for `transition' changes
  1617. if (changed_properties.Contains(PropertyId::Transition))
  1618. {
  1619. dirty_transition = true;
  1620. }
  1621. }
  1622. void Element::OnPseudoClassChange(const String& /*pseudo_class*/, bool /*activate*/) {}
  1623. void Element::OnChildAdd(Element* /*child*/) {}
  1624. void Element::OnChildRemove(Element* /*child*/) {}
  1625. void Element::DirtyLayout()
  1626. {
  1627. if (Element* document = GetOwnerDocument())
  1628. document->DirtyLayout();
  1629. }
  1630. bool Element::IsLayoutDirty()
  1631. {
  1632. if (Element* document = GetOwnerDocument())
  1633. return document->IsLayoutDirty();
  1634. return false;
  1635. }
  1636. Element* Element::GetClosestScrollableContainer()
  1637. {
  1638. using namespace Style;
  1639. Overflow overflow_x = meta->computed_values.overflow_x();
  1640. Overflow overflow_y = meta->computed_values.overflow_y();
  1641. bool scrollable_x = (overflow_x == Overflow::Auto || overflow_x == Overflow::Scroll);
  1642. bool scrollable_y = (overflow_y == Overflow::Auto || overflow_y == Overflow::Scroll);
  1643. scrollable_x = (scrollable_x && GetScrollWidth() > GetClientWidth());
  1644. scrollable_y = (scrollable_y && GetScrollHeight() > GetClientHeight());
  1645. if (scrollable_x || scrollable_y || meta->computed_values.overscroll_behavior() == OverscrollBehavior::Contain)
  1646. return this;
  1647. else if (parent)
  1648. return parent->GetClosestScrollableContainer();
  1649. return nullptr;
  1650. }
  1651. void Element::ProcessDefaultAction(Event& event)
  1652. {
  1653. if (event == EventId::Mousedown)
  1654. {
  1655. const Vector2f mouse_pos(event.GetParameter("mouse_x", 0.f), event.GetParameter("mouse_y", 0.f));
  1656. if (IsPointWithinElement(mouse_pos) && event.GetParameter("button", 0) == 0)
  1657. SetPseudoClass("active", true);
  1658. }
  1659. if (event.GetPhase() == EventPhase::Target)
  1660. {
  1661. switch (event.GetId())
  1662. {
  1663. case EventId::Mouseover: SetPseudoClass("hover", true); break;
  1664. case EventId::Mouseout: SetPseudoClass("hover", false); break;
  1665. case EventId::Focus:
  1666. SetPseudoClass("focus", true);
  1667. if (event.GetParameter("focus_visible", false))
  1668. SetPseudoClass("focus-visible", true);
  1669. break;
  1670. case EventId::Blur:
  1671. SetPseudoClass("focus", false);
  1672. SetPseudoClass("focus-visible", false);
  1673. break;
  1674. default: break;
  1675. }
  1676. }
  1677. }
  1678. const Style::ComputedValues& Element::GetComputedValues() const
  1679. {
  1680. return meta->computed_values;
  1681. }
  1682. void Element::GetRML(String& content)
  1683. {
  1684. // First we start the open tag, add the attributes then close the open tag.
  1685. // Then comes the children in order, then we add our close tag.
  1686. content += "<";
  1687. content += tag;
  1688. for (auto& pair : attributes)
  1689. {
  1690. const String& name = pair.first;
  1691. if (name == "style")
  1692. continue;
  1693. const Variant& variant = pair.second;
  1694. String value;
  1695. if (variant.GetInto(value))
  1696. {
  1697. content += ' ';
  1698. content += name;
  1699. content += "=\"";
  1700. content += value;
  1701. content += "\"";
  1702. }
  1703. }
  1704. const PropertyMap& local_properties = meta->style.GetLocalStyleProperties();
  1705. if (!local_properties.empty())
  1706. content += " style=\"";
  1707. for (const auto& pair : local_properties)
  1708. {
  1709. const PropertyId id = pair.first;
  1710. const Property& property = pair.second;
  1711. content += StyleSheetSpecification::GetPropertyName(id);
  1712. content += ": ";
  1713. content += StringUtilities::EncodeRml(property.ToString());
  1714. content += "; ";
  1715. }
  1716. if (!local_properties.empty())
  1717. content.back() = '\"';
  1718. if (HasChildNodes())
  1719. {
  1720. content += ">";
  1721. GetInnerRML(content);
  1722. content += "</";
  1723. content += tag;
  1724. content += ">";
  1725. }
  1726. else
  1727. {
  1728. content += " />";
  1729. }
  1730. }
  1731. void Element::SetOwnerDocument(ElementDocument* document)
  1732. {
  1733. if (owner_document && !document)
  1734. {
  1735. // We are detaching from the document and thereby also the context.
  1736. if (Context* context = owner_document->GetContext())
  1737. context->OnElementDetach(this);
  1738. }
  1739. // If this element is a document, then never change owner_document.
  1740. if (owner_document != this && owner_document != document)
  1741. {
  1742. owner_document = document;
  1743. for (ElementPtr& child : children)
  1744. child->SetOwnerDocument(document);
  1745. }
  1746. }
  1747. void Element::SetDataModel(DataModel* new_data_model)
  1748. {
  1749. RMLUI_ASSERTMSG(!data_model || !new_data_model, "We must either attach a new data model, or detach the old one.");
  1750. if (data_model == new_data_model)
  1751. return;
  1752. // stop descent if a nested data model is encountered
  1753. if (data_model && new_data_model && data_model != new_data_model)
  1754. return;
  1755. if (data_model)
  1756. data_model->OnElementRemove(this);
  1757. data_model = new_data_model;
  1758. if (data_model)
  1759. ElementUtilities::ApplyDataViewsControllers(this);
  1760. for (ElementPtr& child : children)
  1761. child->SetDataModel(new_data_model);
  1762. }
  1763. void Element::Release()
  1764. {
  1765. if (instancer)
  1766. instancer->ReleaseElement(this);
  1767. else
  1768. Log::Message(Log::LT_WARNING, "Leak detected: element %s not instanced via RmlUi Factory. Unable to release.", GetAddress().c_str());
  1769. }
  1770. void Element::SetParent(Element* _parent)
  1771. {
  1772. // Assumes we are already detached from the hierarchy or we are detaching now.
  1773. RMLUI_ASSERT(!parent || !_parent);
  1774. parent = _parent;
  1775. if (parent)
  1776. {
  1777. // We need to update our definition and make sure we inherit the properties of our new parent.
  1778. DirtyDefinition(DirtyNodes::Self);
  1779. meta->style.DirtyInheritedProperties();
  1780. }
  1781. // The transform state may require recalculation.
  1782. if (transform_state || (parent && parent->transform_state))
  1783. DirtyTransformState(true, true);
  1784. SetOwnerDocument(parent ? parent->GetOwnerDocument() : nullptr);
  1785. if (!parent)
  1786. {
  1787. if (data_model)
  1788. SetDataModel(nullptr);
  1789. }
  1790. else
  1791. {
  1792. auto it = attributes.find("data-model");
  1793. if (it == attributes.end())
  1794. {
  1795. SetDataModel(parent->data_model);
  1796. }
  1797. else if (Context* context = GetContext())
  1798. {
  1799. String name = it->second.Get<String>();
  1800. if (DataModel* model = context->GetDataModelPtr(name))
  1801. {
  1802. model->AttachModelRootElement(this);
  1803. SetDataModel(model);
  1804. }
  1805. else
  1806. Log::Message(Log::LT_ERROR, "Could not locate data model '%s' in element %s.", name.c_str(), GetAddress().c_str());
  1807. }
  1808. }
  1809. }
  1810. void Element::DirtyAbsoluteOffset()
  1811. {
  1812. if (!absolute_offset_dirty)
  1813. DirtyAbsoluteOffsetRecursive();
  1814. }
  1815. void Element::DirtyAbsoluteOffsetRecursive()
  1816. {
  1817. if (!absolute_offset_dirty)
  1818. {
  1819. absolute_offset_dirty = true;
  1820. if (transform_state)
  1821. DirtyTransformState(true, true);
  1822. }
  1823. for (size_t i = 0; i < children.size(); i++)
  1824. children[i]->DirtyAbsoluteOffsetRecursive();
  1825. }
  1826. void Element::UpdateOffset()
  1827. {
  1828. using namespace Style;
  1829. const auto& computed = meta->computed_values;
  1830. Position position_property = computed.position();
  1831. if (position_property == Position::Absolute || position_property == Position::Fixed)
  1832. {
  1833. if (offset_parent != nullptr)
  1834. {
  1835. const Box& parent_box = offset_parent->GetBox();
  1836. Vector2f containing_block = parent_box.GetSize(BoxArea::Padding);
  1837. // If the element is anchored left, then the position is offset by that resolved value.
  1838. if (computed.left().type != Left::Auto)
  1839. relative_offset_base.x = parent_box.GetEdge(BoxArea::Border, BoxEdge::Left) +
  1840. (ResolveValue(computed.left(), containing_block.x) + GetBox().GetEdge(BoxArea::Margin, BoxEdge::Left));
  1841. // If the element is anchored right, then the position is set first so the element's right-most edge
  1842. // (including margins) will render up against the containing box's right-most content edge, and then
  1843. // offset by the resolved value.
  1844. else if (computed.right().type != Right::Auto)
  1845. {
  1846. relative_offset_base.x = containing_block.x + parent_box.GetEdge(BoxArea::Border, BoxEdge::Left) -
  1847. (ResolveValue(computed.right(), containing_block.x) + GetBox().GetSize(BoxArea::Border).x +
  1848. GetBox().GetEdge(BoxArea::Margin, BoxEdge::Right));
  1849. }
  1850. // If the element is anchored top, then the position is offset by that resolved value.
  1851. if (computed.top().type != Top::Auto)
  1852. {
  1853. relative_offset_base.y = parent_box.GetEdge(BoxArea::Border, BoxEdge::Top) +
  1854. (ResolveValue(computed.top(), containing_block.y) + GetBox().GetEdge(BoxArea::Margin, BoxEdge::Top));
  1855. }
  1856. // If the element is anchored bottom, then the position is set first so the element's right-most edge
  1857. // (including margins) will render up against the containing box's right-most content edge, and then
  1858. // offset by the resolved value.
  1859. else if (computed.bottom().type != Bottom::Auto)
  1860. {
  1861. relative_offset_base.y = containing_block.y + parent_box.GetEdge(BoxArea::Border, BoxEdge::Top) -
  1862. (ResolveValue(computed.bottom(), containing_block.y) + GetBox().GetSize(BoxArea::Border).y +
  1863. GetBox().GetEdge(BoxArea::Margin, BoxEdge::Bottom));
  1864. }
  1865. }
  1866. }
  1867. else if (position_property == Position::Relative)
  1868. {
  1869. if (offset_parent != nullptr)
  1870. {
  1871. const Box& parent_box = offset_parent->GetBox();
  1872. Vector2f containing_block = parent_box.GetSize();
  1873. if (computed.left().type != Left::Auto)
  1874. relative_offset_position.x = ResolveValue(computed.left(), containing_block.x);
  1875. else if (computed.right().type != Right::Auto)
  1876. relative_offset_position.x = -1 * ResolveValue(computed.right(), containing_block.x);
  1877. else
  1878. relative_offset_position.x = 0;
  1879. if (computed.top().type != Top::Auto)
  1880. relative_offset_position.y = ResolveValue(computed.top(), containing_block.y);
  1881. else if (computed.bottom().type != Bottom::Auto)
  1882. relative_offset_position.y = -1 * ResolveValue(computed.bottom(), containing_block.y);
  1883. else
  1884. relative_offset_position.y = 0;
  1885. }
  1886. }
  1887. else
  1888. {
  1889. relative_offset_position.x = 0;
  1890. relative_offset_position.y = 0;
  1891. }
  1892. }
  1893. void Element::SetBaseline(float in_baseline)
  1894. {
  1895. baseline = in_baseline;
  1896. }
  1897. enum class RenderOrder {
  1898. StackNegative, // Local stacking context with z < 0.
  1899. Block,
  1900. TableColumnGroup,
  1901. TableColumn,
  1902. TableRowGroup,
  1903. TableRow,
  1904. TableCell,
  1905. Floating,
  1906. Inline,
  1907. Positioned, // Positioned element, or local stacking context with z == 0.
  1908. StackPositive, // Local stacking context with z > 0.
  1909. };
  1910. struct StackingContextChild {
  1911. Element* element = nullptr;
  1912. RenderOrder order = {};
  1913. };
  1914. static bool operator<(const StackingContextChild& lhs, const StackingContextChild& rhs)
  1915. {
  1916. if (int(lhs.order) == int(rhs.order))
  1917. return lhs.element->GetZIndex() < rhs.element->GetZIndex();
  1918. return int(lhs.order) < int(rhs.order);
  1919. }
  1920. // Treat all children in the range [index_begin, end) as if the parent created a new stacking context, by sorting them
  1921. // separately and then assigning their parent's paint order. However, positioned and descendants which create a new
  1922. // stacking context should be considered part of the parent stacking context. See CSS 2, Appendix E.
  1923. static void StackingContext_MakeAtomicRange(Vector<StackingContextChild>& stacking_children, size_t index_begin, RenderOrder parent_render_order)
  1924. {
  1925. std::stable_sort(stacking_children.begin() + index_begin, stacking_children.end());
  1926. for (auto it = stacking_children.begin() + index_begin; it != stacking_children.end(); ++it)
  1927. {
  1928. auto order = it->order;
  1929. if (order != RenderOrder::StackNegative && order != RenderOrder::Positioned && order != RenderOrder::StackPositive)
  1930. it->order = parent_render_order;
  1931. }
  1932. }
  1933. void Element::BuildLocalStackingContext()
  1934. {
  1935. stacking_context_dirty = false;
  1936. Vector<StackingContextChild> stacking_children;
  1937. AddChildrenToStackingContext(stacking_children);
  1938. std::stable_sort(stacking_children.begin(), stacking_children.end());
  1939. stacking_context.resize(stacking_children.size());
  1940. for (size_t i = 0; i < stacking_children.size(); i++)
  1941. stacking_context[i] = stacking_children[i].element;
  1942. }
  1943. void Element::AddChildrenToStackingContext(Vector<StackingContextChild>& stacking_children)
  1944. {
  1945. bool is_flex_container = (GetDisplay() == Style::Display::Flex);
  1946. const int num_children = (int)children.size();
  1947. for (int i = 0; i < num_children; ++i)
  1948. {
  1949. const bool is_non_dom_element = (i >= num_children - num_non_dom_children);
  1950. children[i]->AddToStackingContext(stacking_children, is_flex_container, is_non_dom_element);
  1951. }
  1952. }
  1953. void Element::AddToStackingContext(Vector<StackingContextChild>& stacking_children, bool is_flex_item, bool is_non_dom_element)
  1954. {
  1955. using Style::Display;
  1956. if (!IsVisible())
  1957. return;
  1958. const Display display = GetDisplay();
  1959. RenderOrder order = RenderOrder::Inline;
  1960. bool include_children = true;
  1961. bool render_as_atomic_unit = false;
  1962. if (local_stacking_context)
  1963. {
  1964. if (z_index > 0.f)
  1965. order = RenderOrder::StackPositive;
  1966. else if (z_index < 0.f)
  1967. order = RenderOrder::StackNegative;
  1968. else
  1969. order = RenderOrder::Positioned;
  1970. include_children = false;
  1971. }
  1972. else if (display == Display::TableRow || display == Display::TableRowGroup || display == Display::TableColumn ||
  1973. display == Display::TableColumnGroup)
  1974. {
  1975. // Handle internal display values taking priority over position and float.
  1976. switch (display)
  1977. {
  1978. case Display::TableRow: order = RenderOrder::TableRow; break;
  1979. case Display::TableRowGroup: order = RenderOrder::TableRowGroup; break;
  1980. case Display::TableColumn: order = RenderOrder::TableColumn; break;
  1981. case Display::TableColumnGroup: order = RenderOrder::TableColumnGroup; break;
  1982. default: break;
  1983. }
  1984. }
  1985. else if (GetPosition() != Style::Position::Static)
  1986. {
  1987. order = RenderOrder::Positioned;
  1988. render_as_atomic_unit = true;
  1989. }
  1990. else if (GetFloat() != Style::Float::None)
  1991. {
  1992. order = RenderOrder::Floating;
  1993. render_as_atomic_unit = true;
  1994. }
  1995. else
  1996. {
  1997. switch (display)
  1998. {
  1999. case Display::Block:
  2000. case Display::FlowRoot:
  2001. case Display::Table:
  2002. case Display::Flex:
  2003. order = RenderOrder::Block;
  2004. render_as_atomic_unit = (display == Display::Table || is_flex_item);
  2005. break;
  2006. case Display::Inline:
  2007. case Display::InlineBlock:
  2008. case Display::InlineFlex:
  2009. case Display::InlineTable:
  2010. order = RenderOrder::Inline;
  2011. render_as_atomic_unit = (display != Display::Inline || is_flex_item);
  2012. break;
  2013. case Display::TableCell:
  2014. order = RenderOrder::TableCell;
  2015. render_as_atomic_unit = true;
  2016. break;
  2017. case Display::TableRow:
  2018. case Display::TableRowGroup:
  2019. case Display::TableColumn:
  2020. case Display::TableColumnGroup:
  2021. case Display::None: RMLUI_ERROR; break; // Handled above.
  2022. }
  2023. }
  2024. if (is_non_dom_element)
  2025. render_as_atomic_unit = true;
  2026. stacking_children.push_back(StackingContextChild{this, order});
  2027. if (include_children && !children.empty())
  2028. {
  2029. const size_t index_child_begin = stacking_children.size();
  2030. AddChildrenToStackingContext(stacking_children);
  2031. if (render_as_atomic_unit)
  2032. StackingContext_MakeAtomicRange(stacking_children, index_child_begin, order);
  2033. }
  2034. }
  2035. void Element::DirtyStackingContext()
  2036. {
  2037. // Find the first ancestor that has a local stacking context, that is our stacking context parent.
  2038. Element* stacking_context_parent = this;
  2039. while (stacking_context_parent && !stacking_context_parent->local_stacking_context)
  2040. {
  2041. stacking_context_parent = stacking_context_parent->GetParentNode();
  2042. }
  2043. if (stacking_context_parent)
  2044. stacking_context_parent->stacking_context_dirty = true;
  2045. }
  2046. void Element::DirtyDefinition(DirtyNodes dirty_nodes)
  2047. {
  2048. switch (dirty_nodes)
  2049. {
  2050. case DirtyNodes::Self: dirty_definition = true; break;
  2051. case DirtyNodes::SelfAndSiblings:
  2052. dirty_definition = true;
  2053. if (parent)
  2054. parent->dirty_child_definitions = true;
  2055. break;
  2056. }
  2057. }
  2058. void Element::UpdateDefinition()
  2059. {
  2060. if (dirty_definition)
  2061. {
  2062. dirty_definition = false;
  2063. // Dirty definition implies all our descendent elements. Anything that can change the definition of this element can also change the
  2064. // definition of any descendants due to the presence of RCSS descendant or child combinators. In principle this also applies to sibling
  2065. // combinators, but those are handled during the DirtyDefinition call.
  2066. dirty_child_definitions = true;
  2067. GetStyle()->UpdateDefinition();
  2068. }
  2069. if (dirty_child_definitions)
  2070. {
  2071. dirty_child_definitions = false;
  2072. for (const ElementPtr& child : children)
  2073. child->dirty_definition = true;
  2074. }
  2075. }
  2076. bool Element::Animate(const String& property_name, const Property& target_value, float duration, Tween tween, int num_iterations,
  2077. bool alternate_direction, float delay, const Property* start_value)
  2078. {
  2079. bool result = false;
  2080. PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
  2081. auto it_animation = StartAnimation(property_id, start_value, num_iterations, alternate_direction, delay, false);
  2082. if (it_animation != animations.end())
  2083. {
  2084. result = it_animation->AddKey(duration, target_value, *this, tween, true);
  2085. if (!result)
  2086. animations.erase(it_animation);
  2087. }
  2088. return result;
  2089. }
  2090. bool Element::AddAnimationKey(const String& property_name, const Property& target_value, float duration, Tween tween)
  2091. {
  2092. ElementAnimation* animation = nullptr;
  2093. PropertyId property_id = StyleSheetSpecification::GetPropertyId(property_name);
  2094. for (auto& existing_animation : animations)
  2095. {
  2096. if (existing_animation.GetPropertyId() == property_id)
  2097. {
  2098. animation = &existing_animation;
  2099. break;
  2100. }
  2101. }
  2102. if (!animation)
  2103. return false;
  2104. bool result = animation->AddKey(animation->GetDuration() + duration, target_value, *this, tween, true);
  2105. return result;
  2106. }
  2107. ElementAnimationList::iterator Element::StartAnimation(PropertyId property_id, const Property* start_value, int num_iterations,
  2108. bool alternate_direction, float delay, bool initiated_by_animation_property)
  2109. {
  2110. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == property_id; });
  2111. if (it != animations.end())
  2112. {
  2113. const bool allow_overwriting_animation = !initiated_by_animation_property;
  2114. if (!allow_overwriting_animation)
  2115. {
  2116. Log::Message(Log::LT_WARNING,
  2117. "Could not animate property '%s' on element: %s. "
  2118. "Please ensure that the property does not appear in multiple animations on the same element.",
  2119. StyleSheetSpecification::GetPropertyName(property_id).c_str(), GetAddress().c_str());
  2120. return it;
  2121. }
  2122. *it = ElementAnimation{};
  2123. }
  2124. else
  2125. {
  2126. animations.emplace_back();
  2127. it = animations.end() - 1;
  2128. }
  2129. Property value;
  2130. if (start_value)
  2131. {
  2132. value = *start_value;
  2133. if (!value.definition)
  2134. if (auto default_value = GetProperty(property_id))
  2135. value.definition = default_value->definition;
  2136. }
  2137. else if (auto default_value = GetProperty(property_id))
  2138. {
  2139. value = *default_value;
  2140. }
  2141. if (value.definition)
  2142. {
  2143. ElementAnimationOrigin origin = (initiated_by_animation_property ? ElementAnimationOrigin::Animation : ElementAnimationOrigin::User);
  2144. double start_time = Clock::GetElapsedTime() + (double)delay;
  2145. *it = ElementAnimation{property_id, origin, value, *this, start_time, 0.0f, num_iterations, alternate_direction};
  2146. }
  2147. if (!it->IsInitalized())
  2148. {
  2149. animations.erase(it);
  2150. it = animations.end();
  2151. }
  2152. return it;
  2153. }
  2154. bool Element::AddAnimationKeyTime(PropertyId property_id, const Property* target_value, float time, Tween tween)
  2155. {
  2156. if (!target_value)
  2157. target_value = meta->style.GetProperty(property_id);
  2158. if (!target_value)
  2159. return false;
  2160. ElementAnimation* animation = nullptr;
  2161. for (auto& existing_animation : animations)
  2162. {
  2163. if (existing_animation.GetPropertyId() == property_id)
  2164. {
  2165. animation = &existing_animation;
  2166. break;
  2167. }
  2168. }
  2169. if (!animation)
  2170. return false;
  2171. bool result = animation->AddKey(time, *target_value, *this, tween, true);
  2172. return result;
  2173. }
  2174. bool Element::StartTransition(const Transition& transition, const Property& start_value, const Property& target_value)
  2175. {
  2176. auto it = std::find_if(animations.begin(), animations.end(), [&](const ElementAnimation& el) { return el.GetPropertyId() == transition.id; });
  2177. if (it != animations.end() && !it->IsTransition())
  2178. return false;
  2179. float duration = transition.duration;
  2180. double start_time = Clock::GetElapsedTime() + (double)transition.delay;
  2181. if (it == animations.end())
  2182. {
  2183. // Add transition as new animation
  2184. animations.push_back(ElementAnimation{transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false});
  2185. it = (animations.end() - 1);
  2186. }
  2187. else
  2188. {
  2189. // Compress the duration based on the progress of the current animation
  2190. float f = it->GetInterpolationFactor();
  2191. f = 1.0f - (1.0f - f) * transition.reverse_adjustment_factor;
  2192. duration = duration * f;
  2193. // Replace old transition
  2194. *it = ElementAnimation{transition.id, ElementAnimationOrigin::Transition, start_value, *this, start_time, 0.0f, 1, false};
  2195. }
  2196. bool result = it->AddKey(duration, target_value, *this, transition.tween, true);
  2197. if (result)
  2198. SetProperty(transition.id, start_value);
  2199. else
  2200. animations.erase(it);
  2201. return result;
  2202. }
  2203. void Element::HandleTransitionProperty()
  2204. {
  2205. if (dirty_transition)
  2206. {
  2207. dirty_transition = false;
  2208. // Remove all transitions that are no longer in our local list
  2209. const TransitionList* keep_transitions = GetComputedValues().transition();
  2210. if (keep_transitions && keep_transitions->all)
  2211. return;
  2212. auto it_remove = animations.end();
  2213. if (!keep_transitions || keep_transitions->none)
  2214. {
  2215. // All transitions should be removed, but only touch the animations that originate from the 'transition' property.
  2216. // Move all animations to be erased in a valid state at the end of the list, and erase later.
  2217. it_remove = std::partition(animations.begin(), animations.end(),
  2218. [](const ElementAnimation& animation) -> bool { return !animation.IsTransition(); });
  2219. }
  2220. else
  2221. {
  2222. RMLUI_ASSERT(keep_transitions);
  2223. // Only remove the transitions that are not in our keep list.
  2224. const auto& keep_transitions_list = keep_transitions->transitions;
  2225. it_remove = std::partition(animations.begin(), animations.end(), [&keep_transitions_list](const ElementAnimation& animation) -> bool {
  2226. if (!animation.IsTransition())
  2227. return true;
  2228. auto it = std::find_if(keep_transitions_list.begin(), keep_transitions_list.end(),
  2229. [&animation](const Transition& transition) { return animation.GetPropertyId() == transition.id; });
  2230. bool keep_animation = (it != keep_transitions_list.end());
  2231. return keep_animation;
  2232. });
  2233. }
  2234. // We can decide what to do with cancelled transitions here.
  2235. for (auto it = it_remove; it != animations.end(); ++it)
  2236. RemoveProperty(it->GetPropertyId());
  2237. animations.erase(it_remove, animations.end());
  2238. }
  2239. }
  2240. void Element::HandleAnimationProperty()
  2241. {
  2242. // Note: We are effectively restarting all animations whenever 'dirty_animation' is set. Use the dirty flag with care,
  2243. // or find another approach which only updates actual "dirty" animations.
  2244. if (dirty_animation)
  2245. {
  2246. dirty_animation = false;
  2247. const AnimationList* animation_list = meta->computed_values.animation();
  2248. bool element_has_animations = ((animation_list && !animation_list->empty()) || !animations.empty());
  2249. const StyleSheet* stylesheet = nullptr;
  2250. if (element_has_animations)
  2251. stylesheet = GetStyleSheet();
  2252. if (stylesheet)
  2253. {
  2254. // Remove existing animations
  2255. {
  2256. // We only touch the animations that originate from the 'animation' property.
  2257. auto it_remove = std::partition(animations.begin(), animations.end(),
  2258. [](const ElementAnimation& animation) { return animation.GetOrigin() != ElementAnimationOrigin::Animation; });
  2259. // We can decide what to do with cancelled animations here.
  2260. for (auto it = it_remove; it != animations.end(); ++it)
  2261. RemoveProperty(it->GetPropertyId());
  2262. animations.erase(it_remove, animations.end());
  2263. }
  2264. // Start animations
  2265. if (animation_list)
  2266. {
  2267. for (const auto& animation : *animation_list)
  2268. {
  2269. const Keyframes* keyframes_ptr = stylesheet->GetKeyframes(animation.name);
  2270. if (keyframes_ptr && keyframes_ptr->blocks.size() >= 1 && !animation.paused)
  2271. {
  2272. auto& property_ids = keyframes_ptr->property_ids;
  2273. auto& blocks = keyframes_ptr->blocks;
  2274. bool has_from_key = (blocks[0].normalized_time == 0);
  2275. bool has_to_key = (blocks.back().normalized_time == 1);
  2276. // If the first key defines initial conditions for a given property, use those values, else, use this element's current
  2277. // values.
  2278. for (PropertyId id : property_ids)
  2279. StartAnimation(id, (has_from_key ? blocks[0].properties.GetProperty(id) : nullptr), animation.num_iterations,
  2280. animation.alternate, animation.delay, true);
  2281. // Add middle keys: Need to skip the first and last keys if they set the initial and end conditions, respectively.
  2282. for (int i = (has_from_key ? 1 : 0); i < (int)blocks.size() + (has_to_key ? -1 : 0); i++)
  2283. {
  2284. // Add properties of current key to animation
  2285. float time = blocks[i].normalized_time * animation.duration;
  2286. for (auto& property : blocks[i].properties.GetProperties())
  2287. AddAnimationKeyTime(property.first, &property.second, time, animation.tween);
  2288. }
  2289. // If the last key defines end conditions for a given property, use those values, else, use this element's current values.
  2290. float time = animation.duration;
  2291. for (PropertyId id : property_ids)
  2292. AddAnimationKeyTime(id, (has_to_key ? blocks.back().properties.GetProperty(id) : nullptr), time, animation.tween);
  2293. }
  2294. }
  2295. }
  2296. }
  2297. }
  2298. }
  2299. void Element::AdvanceAnimations()
  2300. {
  2301. if (!animations.empty())
  2302. {
  2303. double time = Clock::GetElapsedTime();
  2304. for (auto& animation : animations)
  2305. {
  2306. Property property = animation.UpdateAndGetProperty(time, *this);
  2307. if (property.unit != Unit::UNKNOWN)
  2308. SetProperty(animation.GetPropertyId(), property);
  2309. }
  2310. // Move all completed animations to the end of the list
  2311. auto it_completed =
  2312. std::partition(animations.begin(), animations.end(), [](const ElementAnimation& animation) { return !animation.IsComplete(); });
  2313. Vector<Dictionary> dictionary_list;
  2314. Vector<bool> is_transition;
  2315. dictionary_list.reserve(animations.end() - it_completed);
  2316. is_transition.reserve(animations.end() - it_completed);
  2317. for (auto it = it_completed; it != animations.end(); ++it)
  2318. {
  2319. const String& property_name = StyleSheetSpecification::GetPropertyName(it->GetPropertyId());
  2320. dictionary_list.emplace_back();
  2321. dictionary_list.back().emplace("property", Variant(property_name));
  2322. is_transition.push_back(it->IsTransition());
  2323. // Remove completed transition- and animation-initiated properties.
  2324. // Should behave like in HandleTransitionProperty() and HandleAnimationProperty() respectively.
  2325. if (it->GetOrigin() != ElementAnimationOrigin::User)
  2326. RemoveProperty(it->GetPropertyId());
  2327. }
  2328. // Need to erase elements before submitting event, as iterators might be invalidated when calling external code.
  2329. animations.erase(it_completed, animations.end());
  2330. for (size_t i = 0; i < dictionary_list.size(); i++)
  2331. DispatchEvent(is_transition[i] ? EventId::Transitionend : EventId::Animationend, dictionary_list[i]);
  2332. }
  2333. }
  2334. void Element::DirtyTransformState(bool perspective_dirty, bool transform_dirty)
  2335. {
  2336. dirty_perspective |= perspective_dirty;
  2337. dirty_transform |= transform_dirty;
  2338. }
  2339. void Element::UpdateTransformState()
  2340. {
  2341. if (!dirty_perspective && !dirty_transform)
  2342. return;
  2343. const ComputedValues& computed = meta->computed_values;
  2344. const Vector2f pos = GetAbsoluteOffset(BoxArea::Border);
  2345. const Vector2f size = GetBox().GetSize(BoxArea::Border);
  2346. bool perspective_or_transform_changed = false;
  2347. if (dirty_perspective)
  2348. {
  2349. // If perspective is set on this element, then it applies to our children. We just calculate it here,
  2350. // and let the children's transform update merge it with their transform.
  2351. bool had_perspective = (transform_state && transform_state->GetLocalPerspective());
  2352. float distance = computed.perspective();
  2353. Vector2f vanish = Vector2f(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f);
  2354. bool have_perspective = false;
  2355. if (distance > 0.0f)
  2356. {
  2357. have_perspective = true;
  2358. // Compute the vanishing point from the perspective origin
  2359. if (computed.perspective_origin_x().type == Style::PerspectiveOrigin::Percentage)
  2360. vanish.x = pos.x + computed.perspective_origin_x().value * 0.01f * size.x;
  2361. else
  2362. vanish.x = pos.x + computed.perspective_origin_x().value;
  2363. if (computed.perspective_origin_y().type == Style::PerspectiveOrigin::Percentage)
  2364. vanish.y = pos.y + computed.perspective_origin_y().value * 0.01f * size.y;
  2365. else
  2366. vanish.y = pos.y + computed.perspective_origin_y().value;
  2367. }
  2368. if (have_perspective)
  2369. {
  2370. // Equivalent to: Translate(x,y,0) * Perspective(distance) * Translate(-x,-y,0)
  2371. Matrix4f perspective = Matrix4f::FromRows( //
  2372. {1, 0, -vanish.x / distance, 0}, //
  2373. {0, 1, -vanish.y / distance, 0}, //
  2374. {0, 0, 1, 0}, //
  2375. {0, 0, -1 / distance, 1} //
  2376. );
  2377. if (!transform_state)
  2378. transform_state = MakeUnique<TransformState>();
  2379. perspective_or_transform_changed |= transform_state->SetLocalPerspective(&perspective);
  2380. }
  2381. else if (transform_state)
  2382. transform_state->SetLocalPerspective(nullptr);
  2383. perspective_or_transform_changed |= (have_perspective != had_perspective);
  2384. dirty_perspective = false;
  2385. }
  2386. if (dirty_transform)
  2387. {
  2388. // We want to find the accumulated transform given all our ancestors. It is assumed here that the parent transform is already updated,
  2389. // so that we only need to consider our local transform and combine it with our parent's transform and perspective matrices.
  2390. bool had_transform = (transform_state && transform_state->GetTransform());
  2391. bool have_transform = false;
  2392. Matrix4f transform = Matrix4f::Identity();
  2393. if (TransformPtr transform_ptr = computed.transform())
  2394. {
  2395. // First find the current element's transform
  2396. const int n = transform_ptr->GetNumPrimitives();
  2397. for (int i = 0; i < n; ++i)
  2398. {
  2399. const TransformPrimitive& primitive = transform_ptr->GetPrimitive(i);
  2400. Matrix4f matrix = TransformUtilities::ResolveTransform(primitive, *this);
  2401. transform *= matrix;
  2402. have_transform = true;
  2403. }
  2404. if (have_transform)
  2405. {
  2406. // Compute the transform origin
  2407. Vector3f transform_origin(pos.x + size.x * 0.5f, pos.y + size.y * 0.5f, 0);
  2408. if (computed.transform_origin_x().type == Style::TransformOrigin::Percentage)
  2409. transform_origin.x = pos.x + computed.transform_origin_x().value * size.x * 0.01f;
  2410. else
  2411. transform_origin.x = pos.x + computed.transform_origin_x().value;
  2412. if (computed.transform_origin_y().type == Style::TransformOrigin::Percentage)
  2413. transform_origin.y = pos.y + computed.transform_origin_y().value * size.y * 0.01f;
  2414. else
  2415. transform_origin.y = pos.y + computed.transform_origin_y().value;
  2416. transform_origin.z = computed.transform_origin_z();
  2417. // Make the transformation apply relative to the transform origin
  2418. transform = Matrix4f::Translate(transform_origin) * transform * Matrix4f::Translate(-transform_origin);
  2419. }
  2420. // 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
  2421. // believe the motivation is. Then we would need to subtract the absolute zero-offsets during geometry submit whenever we have transforms.
  2422. }
  2423. if (parent && parent->transform_state)
  2424. {
  2425. // Apply the parent's local perspective and transform.
  2426. // @performance: If we have no local transform and no parent perspective, we can effectively just point to the parent transform instead of
  2427. // copying it.
  2428. const TransformState& parent_state = *parent->transform_state;
  2429. if (auto parent_perspective = parent_state.GetLocalPerspective())
  2430. {
  2431. transform = *parent_perspective * transform;
  2432. have_transform = true;
  2433. }
  2434. if (auto parent_transform = parent_state.GetTransform())
  2435. {
  2436. transform = *parent_transform * transform;
  2437. have_transform = true;
  2438. }
  2439. }
  2440. if (have_transform)
  2441. {
  2442. if (!transform_state)
  2443. transform_state = MakeUnique<TransformState>();
  2444. perspective_or_transform_changed |= transform_state->SetTransform(&transform);
  2445. }
  2446. else if (transform_state)
  2447. transform_state->SetTransform(nullptr);
  2448. perspective_or_transform_changed |= (had_transform != have_transform);
  2449. }
  2450. // A change in perspective or transform will require an update to children transforms as well.
  2451. if (perspective_or_transform_changed)
  2452. {
  2453. for (size_t i = 0; i < children.size(); i++)
  2454. children[i]->DirtyTransformState(false, true);
  2455. }
  2456. // No reason to keep the transform state around if transform and perspective have been removed.
  2457. if (transform_state && !transform_state->GetTransform() && !transform_state->GetLocalPerspective())
  2458. {
  2459. transform_state.reset();
  2460. }
  2461. }
  2462. void Element::OnStyleSheetChangeRecursive()
  2463. {
  2464. meta->effects.DirtyEffects();
  2465. OnStyleSheetChange();
  2466. // Now dirty all of our descendants.
  2467. const int num_children = GetNumChildren(true);
  2468. for (int i = 0; i < num_children; ++i)
  2469. GetChild(i)->OnStyleSheetChangeRecursive();
  2470. }
  2471. void Element::OnDpRatioChangeRecursive()
  2472. {
  2473. meta->effects.DirtyEffects();
  2474. GetStyle()->DirtyPropertiesWithUnits(Unit::DP_SCALABLE_LENGTH);
  2475. OnDpRatioChange();
  2476. // Now dirty all of our descendants.
  2477. const int num_children = GetNumChildren(true);
  2478. for (int i = 0; i < num_children; ++i)
  2479. GetChild(i)->OnDpRatioChangeRecursive();
  2480. }
  2481. void Element::DirtyFontFaceRecursive()
  2482. {
  2483. // Dirty the font size to force the element to update the face handle during the next Update(), and update any existing text geometry.
  2484. meta->style.DirtyProperty(PropertyId::FontSize);
  2485. meta->computed_values.font_face_handle(0);
  2486. const int num_children = GetNumChildren(true);
  2487. for (int i = 0; i < num_children; ++i)
  2488. GetChild(i)->DirtyFontFaceRecursive();
  2489. }
  2490. void Element::ClampScrollOffset()
  2491. {
  2492. const Vector2f new_scroll_offset = {
  2493. Math::Round(Math::Min(scroll_offset.x, GetScrollWidth() - GetClientWidth())),
  2494. Math::Round(Math::Min(scroll_offset.y, GetScrollHeight() - GetClientHeight())),
  2495. };
  2496. if (new_scroll_offset != scroll_offset)
  2497. {
  2498. scroll_offset = new_scroll_offset;
  2499. DirtyAbsoluteOffset();
  2500. }
  2501. // At this point the scrollbars have been resolved, both in terms of size and visibility. Update their properties
  2502. // now so that any visibility changes in particular are reflected immediately on the next render. Otherwise we risk
  2503. // that the scrollbars renders a frame late, since changes to scrollbars can happen during layouting.
  2504. meta->scroll.UpdateProperties();
  2505. }
  2506. void Element::ClampScrollOffsetRecursive()
  2507. {
  2508. ClampScrollOffset();
  2509. const int num_children = GetNumChildren();
  2510. for (int i = 0; i < num_children; ++i)
  2511. GetChild(i)->ClampScrollOffsetRecursive();
  2512. }
  2513. } // namespace Rml