Element.cpp 84 KB

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