Element.cpp 82 KB

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