Element.cpp 77 KB

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