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