Element.cpp 73 KB

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