Element.cpp 75 KB

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