Element.cpp 90 KB

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