Element.cpp 74 KB

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