Element.cpp 84 KB

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