Element.cpp 86 KB

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