Element.cpp 86 KB

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