Element.cpp 76 KB

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