Element.cpp 88 KB

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