Element.cpp 71 KB

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