Element.cpp 79 KB

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