Element.cpp 82 KB

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