Element.cpp 81 KB

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