Element.cpp 82 KB

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