Element.cpp 71 KB

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