Element.cpp 85 KB

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