Element.cpp 79 KB

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