Element.cpp 73 KB

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