Element.cpp 72 KB

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