Element.cpp 86 KB

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