Element.cpp 78 KB

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