Element.cpp 75 KB

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