Element.cpp 79 KB

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