Element.cpp 86 KB

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