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