Element.cpp 73 KB

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