Element.cpp 71 KB

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