Element.cpp 71 KB

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