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